Adding arrays with same values to HashSet results in duplicate items

后端 未结 2 824
有刺的猬
有刺的猬 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:48

    The reason the HashSet> works is because the HashSet will use .equals() comparison to decide if you're inserting the same object twice. In the case of List, two lists of the same base type (e.g. ArrayList) with the same content, in the same order, will compare as equal. Thus you're telling the HashSet to insert the same object twice. It only takes a single instance once.

    When you try to do that same operation with an array. See this post: equals vs Arrays.equals in Java for more details about array comparisons in Java. When you insert two arrays, the default .equals() tests if they are the same object, which they are not. Thus it fails.

提交回复
热议问题