I am writing a method that calls a recursive helper method to basically see if the elements of two ArrayList
s are equal and return true if so. I realized, when testing, that the method returns true even if the two ArrayList
s are of same lengths and same first and last elements but different elements in between, which I do not want. I think the method works otherwise. Any suggestions or hints on how I could fix this?
public static boolean isEqual(ArrayList<T> list1,
ArrayList<T> list2) {
return isEqual(list1,list2,0);
}
private static boolean isEqual(ArrayList<T> list1,
ArrayList<T> list2, int n) {
if (n==0 && list1.size()==0 && list1.size() == list2.size())
return true;
else if (n>=list1.size() || n>=list2.size())
return false;
if (n<list1.size() && list1.size() == list2.size()) {
if (list1.get(n).equals((list2.get(n))))
return true;
else
return false;
}
return isEqual(list1, list2, n + 1);
}
Your problem is here :
if (n<list1.size() && list1.size() == list2.size()) {
if (list1.get(n).equals((list2.get(n))))
return true; // don't return true here, since you just tested one element
else
return false;
}
return isEqual(list1, list2, n + 1);
Change it to :
if (n<list1.size() && list1.size() == list2.size()) {
if (!list1.get(n).equals((list2.get(n))))
return false;
}
return isEqual(list1, list2, n + 1);
You'll have to add another stopping condition in which you return true, though.
if (n == list1.size() && list1.size() == list2.size())
return true;
This means that the lists have the same length, and you already compared all the elements successfully.
You should probably add a check on the list sizes and return immediately false if the lists have different sizes. There's no point in doing any recursive calls in this case.
if (n==0 && list1.size() != list2.size())
return false;
Btw, here's shorter recursive version:
public static <T> boolean listsEqual(List<T> l1, List<T> l2) {
return l1.size() == l2.size() && (l1.isEmpty() || listsEqual(l1, l2, l1.size()));
}
private static <T> boolean listsEqual(List<T> l1, List<T> l2, int size) {
// l1.size() == l2.size() == size here
return size == 0 || (l1.get(size - 1).equals(l2.get(size - 1)) && listsEqual(l1, l2, size - 1));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.