How to use Java 7+ 'Objects.hash()' with arrays?
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.
@Overridepublic 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:
@Overridepublic int hashCode() { return HashUtils.deepHashCode(field1, field2, array1, array2);}