I really like Java 7+ style of writing hashCode()
method:
@Override
public int hashCode() {
Objects.hash(field1, field2);
}
It doesn't work correctly with arrays though. The following code:
@Override
public int hashCode() {
Objects.hash(field1, field2, array1, array2);
}
will not work, as for array1
and array2
regular hashCode()
instead of Arrays.hashCode()
would be invoked.
How can I use Objects.hash()
with arrays in a proper way?
You could try:
Objects.hash(field1, field2, Arrays.hashCode(array1), Arrays.hashCode(array2));
This is the same as creating one array that contains field1
, field2
, the contents of array1
and the contents of array2
. Then computing Arrays.hashCode
on this array.