HashSet与int数组的用法 [英] HashSet usage with int arrays

查看:84
本文介绍了HashSet与int数组的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我有一个包含重复项的int数组的ArrayList,所以我想使用HashSet.不幸的是,我无法按需使用HashSet:

As I have an ArrayList of int arrays which contains duplicates, I'd like to use HashSet. Unfortunately, I can't manage to use HashSet as I wish:

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]

有人可以告诉我我错了吗?

Could anybody tell me where I'm wrong ?

先谢谢了 Dominique(java新手)

Thanks in advance Dominique (java newbie)

推荐答案

数组不会覆盖Object类中实现的hashCodeequals,因此,两个数组a1和a2将被视为与仅当a1 == a2(在您的情况下为假)时,彼此之间才能通过HashSet相互连接.

Arrays don't override hashCode and equals implemented in Object class, and therefore, two arrays a1 and a2 will be considered as identical to each other by HashSet only if a1==a2, which is false in your case.

如果使用ArrayList而不是数组,则将解决您的问题,因为对于ArrayList而言,相等性取决于列表成员的相等性(及其出现的顺序).

If you use ArrayLists instead of arrays, your problem will be solved, since for ArrayLists equality is determined by the equality of the members of the lists (and the order in which they appear).

这篇关于HashSet与int数组的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆