Reputation: 3652
What is the Versatile and Simplest way to check if these 2 lists are equaled:
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 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 out "false"
other suggest using containsAll
if(list1.containsAll(list2)){
System.out.println("true");
}
else{
System.out.println("false");
}
but it also prints out "false"
seem the 2 above solutions only work with List but not work with List<String[]>
or even more complicated List<List<String[]>>
So is there any versatile way to check whether any 2 lists are equaled.
Upvotes: 4
Views: 69
Reputation: 21961
boolean isEqual=Arrays.deepEquals(list1.toArray(), list2.toArray());
It is also return true
for 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.
According to docs,
- Returns true if the two specified arrays are deeply equal to one another. Unlike the equals(Object[],Object[]) method, this method is appropriate for use with nested arrays of arbitrary depth.
Upvotes: 5