13

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?

2
  • 2
    You'd probably have to use Arrays.deepHashCode. Commented May 21, 2015 at 22:02
  • 1
    @LouisWasserman - can you elaborate why may I need to use deep hash code? Commented May 21, 2015 at 22:06

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

7

Arrays.deepHashCode will discover arrays in the array (via instanceof Object[]) and recursively call itself. See the code.

If the array contains other arrays as elements, the hash code is based on their contents and so on, ad infinitum.

@Override
public int hashCode() {
    Object[] fields = {field1, field2, array1, array2};
    return Arrays.deepHashCode(fields);
}

It would be useful to have a params version like Objects.hash, but you'd have to write your own:

public final class HashUtils {
    private HashUtils(){}

    public static int deepHashCode(Object... fields) {
        return Arrays.deepHashCode(fields);
    }
}

Usage:

@Override
public int hashCode() {
    return HashUtils.deepHashCode(field1, field2, array1, array2);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.