2015-02-05 67 views
3

由于我有一个包含重复项的int数组的ArrayList,我想使用HashSet。不幸的是,我不能管理,因为我想使用HashSet的:int数组的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] 

有谁告诉我,我错了?

预先感谢 多米尼克(java的新手)

回答

7

阵列不重写hashCodeequalsObject类中实现的,因此,两个阵列a1和a2将HashSet仅当被认为是彼此相同a1 == a2,在你的情况下是错误的。

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

+0

好的。我现在更好地理解。感谢大家的迅速回答 – Dominique 2015-02-05 14:29:12

0

单独添加每个号码。不要用相同的值添加Arrays to HashSet

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

两个阵列,不必equal(他们使用默认Object定义equals()方法,其中比较引用

1

这是因为HashSet使用.equals()看如果新对象被复制(并且.hashCode()来确定“桶”)。

当您使用阵列时,请注意,new int[]{1,2,3}不等于“new int[]{1,2,3}”。

“深度比较”阵列的正确方法是通过Arrays.equals(a, b)方法。

为了有效解决您的问题,您应该创建一个包装类,其中包含您的int[]阵列,然后正确执行.hashCode()equals()。 OK。

+0

非常好的解释。 – Loga 2015-02-05 12:52:12