使用HashSet与int数组的用法

10

我有一个包含重复项的整数数组列表,我希望使用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));
    }

它会导致:

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]

有人能告诉我错在哪里吗?

先谢谢了。 Dominique(Java 新手)

3个回答

28

数组不会覆盖在Object类中实现的hashCodeequals方法,因此,只有当a1==a2时,HashSet将认为两个数组a1和a2是相同的,在您的情况下这是错误的。

如果您使用ArrayList而不是数组,则可以解决您的问题,因为对于ArrayList,相等性是由列表成员的相等性(以及它们出现的顺序)确定的。


5
这是因为HashSet使用.equals()来查看新对象是否重复(并使用.hashCode()确定“桶”)。
当您使用数组时,请注意new int[]{1,2,3}new int[]{1,2,3}不相等。
"深度比较"数组的正确方法是通过Arrays.equals(a, b)方法。
要有效地解决问题,您应该创建一个包含int[]数组的包装类,然后正确实现.hashCode()equals()

0

逐个添加每个数字。不要将数组添加到HashSet中。

    int[] arr1 = {1,2,3};
    int[] arr2 = {1,2,3};
    System.out.println(arr1==arr2);//false
    System.out.println(arr1.equals(arr2)); //false

具有相同值的两个数组不一定是相等的(它们使用在Object中定义的默认equals()方法来比较引用)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接