【发布时间】:2016-03-22 00:31:40
【问题描述】:
我正在尝试检查两个数组是否具有相同的长度,以及相同的位置是否具有相同的值。
我当前的代码如下所示:
public class MyArray {
private int size;
private int[] array;
private boolean isSorted; //to check if array is sorted
private static int arrCount; //used to identify which MyArray object
public MyArray(){
size = 10;
array = new int[10];
arrCount+=1;
}
public MyArray(int Size){
size = Size;
array = new int[Size];
arrCount+=1;
}
public MyArray(MyArray arrOther){
this.size = arrOther.getSize();
this.array = arrOther.getArray();
arrCount+=1;
}
public int getSize(){
return size;
}
public int[] getArray(){
return array;
}
@Override
public boolean equals(Object other){
if (other instanceof MyArray){
MyArray second = (MyArray) other;
if (second.getSize() == this.getSize())
return equalsHelper(this.getArray(), second.getArray(), 0, (size-1));
}
//else
return false;
}
private boolean equalsHelper(int[] first, int[] second, int iStart, int iEnd) {
if (iStart == iEnd) {
return true;
}
if (first[iStart] == second[iStart]) {
if (equalsHelper(first, second, (iStart + 1), iEnd)) {
return true;
}
}
return false;
}
}//end class
由于某种原因,即使数组的顺序不同,它也总是返回 true。
这里在主程序中调用了equals方法:
--main method--
if (MA2.equals(MA1)) //the arrays are identical here
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
MA2.sort(); //the order of the elements changes
System.out.println("The second array has been sorted in ascending order.");
if (MA2.equals(MA1))
{
System.out.println("The first and second arrays are equal.");
}
else {System.out.println("The first and second arrays are NOT equal.");}
【问题讨论】:
-
无法重现“始终返回 true”:请参阅 IDEONE。比较两个
1, 2, 3数组返回 true,正如预期的那样,比较1, 1, 1和1, 2, 3返回 false。 -
昨天的这个答案有什么问题? stackoverflow.com/a/36120985/3973077
-
“我不确定是否应该使用 == 运算符或 .equals() 调用该方法” 您绝对应该使用
equals()调用该方法。如果你用==“调用”,你根本不是在调用你的代码,而只是在比较对象身份,如果是这样,那么我就赢了,因为错误出现在调用者而不是显示的代码。 -
我通过创建一个新数组并将另一个数组的值复制到新数组中来替换它。原来我的第二个数组是指向第一个数组的指针……哈哈