有人知道判断两个数组列表是否包含相同值的有效方法吗?
代码:
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
挑战在于数组列表的值顺序不同..
(foo, baa) == (foo, baa) // per definition :)
我需要得到这个
(foo, baa) == (baa, foo) // true
那么您的方法是什么?
最佳答案
先排序吧。
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);
}
老实说,您应该检查一下您的数据结构决策。这看起来更像是一个集合问题。先排序再比较的时间复杂度为 O(nlog n),而 HashSet
比较的时间复杂度仅为 O(n)。
关于Java比较无序的ArrayLists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20054737/