Java 不能在类中的两个数组之间使用equal运算符来模拟ArrayList的工作方式
因此,作为练习,我创建了这个类“Array”,以模拟普通ArrayList如何使用我想要的一些附加函数 我遇到了一个名为“intersect”的方法的问题。 在这个方法中,假设它获取两个输入的数组(来自我创建的数组类)对象,并比较其中的值。如果两个数组之间有公共数字,它将创建一个新数组并将它们放入这个新数组中。这样,我可以打印这个新数组中的值 但是,我不能在这里使用equal运算符,因为我需要的是普通的Java数组类型,而不是我为使用的参数“Array secondArray”创建的类。 因此,我可以这样使用If语句: if(数组[i]==secondArray[j]) 我怎样才能解决这个问题 这是主类:Java 不能在类中的两个数组之间使用equal运算符来模拟ArrayList的工作方式,java,arrays,arraylist,Java,Arrays,Arraylist,因此,作为练习,我创建了这个类“Array”,以模拟普通ArrayList如何使用我想要的一些附加函数 我遇到了一个名为“intersect”的方法的问题。 在这个方法中,假设它获取两个输入的数组(来自我创建的数组类)对象,并比较其中的值。如果两个数组之间有公共数字,它将创建一个新数组并将它们放入这个新数组中。这样,我可以打印这个新数组中的值 但是,我不能在这里使用equal运算符,因为我需要的是普通的Java数组类型,而不是我为使用的参数“Array secondArray”创建的类。 因此,
package com.company;
public static void main(String[] args) {
Array array = new Array(3);
Array array1 = new Array(3);
array.insert(1);
array.insert(2);
array.insert(3);
array1.insert(2);
array1.insert(3);
array1.insert(4);
array.print();
}
}
下面是我制作的数组类:
public class Array {
int length;
Integer[] array;
public Array(int length) {
array = new Integer[this.length=length];
}
public void insert(int item) {
if (array[length - 1] == null) { //if there is no value in the last index
for (int i = 0; i < length; i++) {
if (array[i] == null) {
array[i] = item;
break;
}
}
} else if (array[length - 1] != null) { //if there is a value in the last index
int newLength = this.length + 1;
Integer[] newArray = new Integer[newLength];
for (int j = 0; j < newLength; j++) {
for (int i = 0; i < length; i++) {
if (i == j) {
newArray[j] = array[i];
}
}
}
newArray[newLength - 1] = item;
this.array = newArray;
this.length = newLength;
}
}
public int intersect(Array secondArray) {
//Store array1 and array2
//Go through all of the values in each array
//If the values are equal, store them in another array
Integer[] commonValues = new Integer[length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < secondArray.length; j++) {
if (array[i] == secondArray[j]) {
}
}
}
return commonValues[0];
}
公共类数组{
整数长度;
整数[]数组;
公共数组(整数长度){
数组=新整数[this.length=length];
}
公共空白插入(整数项){
if(array[length-1]==null){//如果最后一个索引中没有值
for(int i=0;i
}
但是,我不能在这里使用相等运算符,因为我需要法线
Java数组类型,而不是我为参数“Array”创建的类
我使用的第二个数组。因此,我可以使用If语句
如下所示:if(数组[i]==secondArray[j])
由于java不支持将允许您编写
myCustomArray[i]==myCustomArray2[i]
,所以您需要使用该方法来获取元素。执行如下操作:myCustomArray.get(i)==myCustomArray2.get(i)
您的insert
方法很奇怪。因为每次只增加长度1,所以在第一次击中第二个分支后,始终会击中该分支。而且不需要嵌套循环:只需删除外部循环;或者使用this.array=Arrays.copyOfRange(this.array,newLength)
。感谢您的回答@AndyTurner!我需要再复习一下intersect方法,但我的目标是在不使用任何数组方法的情况下完成它。这也是我想的,但我想可能有一种更简单的方法,或者我不理解的东西。好吧,我想我得试试这个。哇,这是非常方便的C#有自定义索引器(我第一次听到这个词)!