有没有办法删除 ArrayList
中的重复数组?
我尝试将 ArrayList
转换为 HashSet
,然后再转换回来以删除重复的数组。
但这是行不通的:
ArrayList<int[]> mylist = new ArrayList<int[]>();
mylist.add(new int[]{1,2});
mylist.add(new int[]{2,2}); // Duplicate
mylist.add(new int[]{2,2}); // Duplicate
之前:
{{1,2},{2,2},{2,2}}
之后:
{{1,2},{2,2}}
最佳答案
不同的数组对象即使内容相同,也有不同的 hashCode() 值。
顺便说一句,我想不出还有什么比将数组包装到一个类中并使用基于值的 hashCode 和 Arrays.equals 作为 equals 来散列所有包装的数组更好的了。
这将是 O(n),而不是在嵌套循环中搜索重复项 (O(n^2))。
关于java - 删除 ArrayList 中的重复数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973394/