Is there a universal and easy way to check if any 2 lists of String [] or String [] [] ... are the same?

What is a universal and easy way to check if these 2 lists are equal:

            List<String[]> list1=new ArrayList<String[]>();
            String[] s1={"1","2"};
            String[] s2={"3","4"};
            list1.add(s1);
            list1.add(s2);

            List<String[]> list2=new ArrayList<String[]>();
            String[] s3={"1","2"};
            String[] s4={"3","4"};
            list2.add(s3);
            list2.add(s4);

Some solutions on the Internet suggest using Collections.sort

Collections.sort(list1);
Collections.sort(list2);

if(list1.equals(list2)){
    System.out.println("true");
}
else{
    System.out.println("false");
}

but it prints "false" others suggest using containsAll

if(list1.containsAll(list2)){
     System.out.println("true");
}
else{
     System.out.println("false");
}

but also prints “false” it seems that the 2 above solutions work only with a list, but do not work with List<String[]>or even more complex List<List<String[]>> So, is there a universal way to check if any 2 lists are equal.

+4
source share
1 answer

Use Arrays.deepEquals

boolean isEqual=Arrays.deepEquals(list1.toArray(), list2.toArray());

It also returns truefor List<String[][]>, for example

    List<String[][]> list1 = new ArrayList<String[][]>();
    String[][] s1 = {{"1", "2"}, {"1", "2"}};
    String[][] s2 = {{"3", "4"}, {"3", "4"}};
    list1.add(s1);
    list1.add(s2);

    List<String[][]> list2 = new ArrayList<String[][]>();
    String[][] s3 = {{"1", "2"}, {"1", "2"}};
    String[][] s4 = {{"3", "4"}, {"3", "4"}};
    list2.add(s3);
    list2.add(s4);

    boolean isEqual = Arrays.deepEquals(list1.toArray(), list2.toArray());

    System.out.println(isEqual);//will  print true.

docs,

  • true, . equals (Object [], Object []), .
+5

All Articles