简体   繁体   English

ArrayList比较与递归方法

[英]ArrayList comparison with a recursive method

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. 我正在编写一个方法,该方法调用递归帮助器方法,以基本上查看两个ArrayList的元素是否相等,如果相等,则返回true。 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. 我意识到,在测试时,即使两个ArrayList的长度相同,并且第一个和最后一个元素相同,但它们之间的元素不同,该方法也返回true,这是我不希望的。 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. 但是,您必须添加另一个停止条件,在该条件中您将返回true。

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. 您可能应该对列表大小进行检查,如果列表大小不同,则立即返回false。 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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM