Adding arrays with same values to HashSet results in duplicate items

后端 未结 2 823
有刺的猬
有刺的猬 2020-12-11 03:01

I\'m trying to create a set of arrays of ints, the thing is that if I try to do:

HashSet s = new HashSet();
int a1[] = {1,2,3};
int         


        
2条回答
  •  臣服心动
    2020-12-11 03:42

    It has nothing to do with collision at the end of the day:

    a1.equals(a2) == false
    

    Since they are not equal, a Set will treat them as different.

    Note Array in Java does not override the equals method from Object.

    And since add in Set is defined as

    More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2))

    is seems to be impossible to properly implement a Set that might meet your requirement (compare elements with Arrays.equals) without violating some contracts.

提交回复
热议问题