HashSet usage with int arrays

后端 未结 3 880
说谎
说谎 2020-12-06 19:33

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         


        
相关标签:
3条回答
  • 2020-12-06 19:48

    That's because HashSet uses .equals() to see if a new object is duplicated (and .hashCode() to determine the "bucket").

    When you work with arrays, please be aware that new int[]{1,2,3} is NOT "equal to" new int[]{1,2,3}.

    The proper way to "deep compare" arrays is via Arrays.equals(a, b) method.

    To solve your problem situation effectively you should create a wrapper class which contains your int[] array and then implement .hashCode() and equals() properly.

    0 讨论(0)
  • 2020-12-06 19:56

    Add each number individually. Don't add 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
    

    Two arrays with same values need not be equal (they use default equals() method defined in Object which compares references.)

    0 讨论(0)
  • 2020-12-06 20:07

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

    0 讨论(0)
提交回复
热议问题