[英]Comparing the values of two arrays using recursion?
我試圖檢查兩個數組是否具有相同的長度,並且在相同的確切位置具有相同的值。
我當前的代碼如下所示:
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.");}
首先檢查(最好)在您的助手之外應該是查看兩個數組是否具有相等的長度。 否則繼續下去是沒有意義的。
如果到達數組末尾, equalsHelper
應該返回 true。
我認為沒有理由為索引使用 2 個單獨的指針,因為數組需要具有相同的大小並且正在檢查相同的索引。
調用:
....
....
if(first.length != second.length)
return false;
return equalsHelper(first, second, 0);
輔助方法...
private boolean equalsHelper(int[] first, int[] second, int indx) {
if(indx == first.length)
return true;
if(first[indx] != second[indx)
return false;
return equalsHelper(first, second, indx+1);
}
首先,iStart 和 iEnd 是多余的。 使用.length
String[] array = new String[10];
int size = array.length;
如果您嘗試比較可能相同的數組的內容,則需要手動傳遞它。
for(int i = 0: (i > first.length || i > second.length; i++){
if(first[i] != second[i]){
return false;
}
}
return true
你的下一個問題是
if (iStart == iEnd){
return first[iEnd] == second[iEnd]; //return true or false
你這里的邏輯是錯誤的。 你不能像這樣直接比較數組。 它正在比較內存地址。 除非您在調用該方法時通過完全相同的數組,否則這將始終為 false - 我認為這不是您想要做的
數組長度是手動設置的,所以這是有意識的努力來獲得差異。
如果您期望不同的長度,我建議您使用ArrayList 。 它們也更靈活。
ArrayList <Integer> a = new ArrayList <int>();
ArrayList <Integer> b = new ArrayList <int>();
然后你需要檢查它們的長度。 ArrayList 使用 .length() 方法而不是 Array[].length 屬性
if(a.length() == b.length()){
然后,如果您想查看每個索引中的每個值是否相同,則需要手動傳遞數組,如上所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.