2个arraylist是否相等

时间:2019-10-20 12:17:59

标签: arraylist equality

public boolean isSymmetric(TreeNode A) {
        if(A==null)
            return true;
     /*   if(isSymmetric(A.left) && isSymmetric(A.right))
            return 1;
        else return 0;*/
        ArrayList<Integer> al1= preorder(A);
        System.out.println(al1);
        al.clear(); 
        //System.out.println("common "+al);
        p=invertTree(A);
        ArrayList<Integer> al2= preorder(p);
        System.out.println(al2);
        int i=0,j=0;
        while(i<al1.size() && i<al2.size())
        {
            System.out.println(al1.get(i)+" "+al2.get(i));
            if(al1.get(i)!=al2.get(i))
                    return false;
            i++;
        }
        return true;
    }

我正在尝试比较2个arraylist是否具有相同顺序的相同元素

您的输入

  

[1,2,2,null,3,null,3]

stdout

  

[1,2,-1,3,-1,-1,2,-1,3,-1,-1] //印有al1

     

[1、2、3,-1,-1,-1、2、3,-1,-1,-1] //已打印的al2

     

1 1 2 2 3 3

     

-1 -1

     

-1 -1

     

-1 -1 2 2 3 3

     

-1 -1

     

-1 -1

     

-1 -1

//不知道它们如何显示相同的元素 输出量 是

预期 错误

1 个答案:

答案 0 :(得分:0)

让我们假设您有al1和al2 ArrayList。这样可以检查它们是否相等(所有位置的大小和值均相同)

boolean same = true;
if ((al1 == null) != (al2 == null)) {
    same = false;
} 
if (al1.size() != al2.size()) {
    same = false;
} else {
    for (int i = 0; same && (same = al1.get(i).equals(al2.get(i)); i++);
    //The result is in same
}
相关问题