Java compares unordered ArrayLists
•
Java
Does anyone know an effective way to determine whether two ArrayLists contain the same value?
Code:
ArrayList<String> dummy1= new ArrayList<String>();
list1.put("foo");
list1.put("baa");
ArrayList<String> dummy2= new ArrayList<String>();
list1.put("baa");
list1.put("foo");
dummy1 == dummy2
The challenge is that ArrayLists do not have the same value order
(foo,baa) == (foo,baa) // per deFinition :)
I need this
(foo,baa) == (baa,foo) // true
So what's your method?
Solution
Sort it first
public boolean equalLists(List<String> one,List<String> two){
if (one == null && two == null){
return true;
}
if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}
//to avoid messing the order of the lists we will use a copy
//as noted in comments by A. R. S.
one = new ArrayList<String>(one);
two = new ArrayList<String>(two);
Collections.sort(one);
Collections.sort(two);
return one.equals(two);
}
To be honest, you should check your data structure decisions This seems more like a problem Sorting and then comparison will take o (NLog n), while HashSet comparison will only take o (n)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
