A. Mashreghi A. Mashreghi - 1 year ago 75
Java Question

HashSet is not sensitive to content of array?

how can I make this code work such that when I change the content of the array, HashSet considers a different hashcode for it? Right now it prints "true". I want it to print true if and only if the elements are exactly the same.

HashSet<int[][]> x = new HashSet<int[][]>();
int a[][] = {{1, 2}, {3, 4}};
a[0][0] = 2;
a[0][1] = 1;

Answer Source

Unfortunately, we need to comply with the directive not to mix arrays and collections as far as possible while programming in Java. But in this particular case, I am not sure why you don't like the default behavior. What you are effectively doing is

  1. add an object a to a set (no matter a is an array)
  2. check if that same object (which has the same reference a) is in the set.

There is no way the contains check is going to be false in this case. And more importantly, don't you want this to be true?

As a Java novice (not implying that you are), I would have been more surprised with the following:

    HashSet<int[][]> x = new HashSet<>();
    int a[][] = {{1, 2}, {3, 4}};
    int[][] b = {{1, 2}, {3, 4}};

which prints


This is where the complication with respect to hashCode implementation of arrays in Java becomes evident. You try to reason that clearly b is same as a, and yet the set says it contains a and does not contain b.