Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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("
TESTs
");
    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));
    }

It results in:

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 ?

Thanks in advance Dominique (java newbie)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...