因为我有一个包含重复项的int数组的ArrayList,所以我想使用HashSet.不幸的是,我无法按照自己的意愿使用HashSet:
System.out.print("\nTESTs\n");
ArrayList<int[]> list = new ArrayList<int[]>();
list.add(new int[]{1,2,3});
list.add(new int[]{5,1,1});
list.add(new int[]{1,2,3});//duplicate
list.add(new int[]{5,1,3});
Set<int[]> set = new HashSet<int[]>(list);
System.out.println("Size of the set = "+set.size());
ArrayList<int[]> arrayList = new ArrayList<int[]>(set);
System.out.println("Size of the arrayList = "+arrayList.size());
for (int[] array:arrayList){
System.out.println(Arrays.toString(array));
}
Run Code Online (Sandbox Code Playgroud)
它导致:
Size of the set = 4
Size of the arrayList = 4
[1, 2, 3]
[1, 2, 3] // duplicate still here
[5, 1, 1]
[5, 1, 3]
Run Code Online (Sandbox Code Playgroud)
有谁能告诉我我哪里错了?
在此先感谢Dominique(java新手)
数组不会在类中重写hashCode和equals实现Object,因此,HashSet只有当a1 == a2时,两个数组a1和a2才会被视为彼此相同,在您的情况下为false.
如果使用ArrayLists而不是数组,则问题将得到解决,因为ArrayLists相等性由列表成员的相等性(以及它们出现的顺序)决定.
这是因为HashSet用于.equals()查看新对象是否重复(并.hashCode()确定“存储桶”)。
当您使用数组时,请注意new int[]{1,2,3}不是“等于” new int[]{1,2,3}。
“深度比较”数组的正确方法是通过Arrays.equals(a, b)方法。
为了有效地解决您的问题情况,您应该创建一个包含int[]数组的包装类,然后.hashCode()正确实现equals()。