Search code examples
javaguavaapache-commonsguava-testlib

Hashcode with generic types


Looking for a method to easily calculate hashes for arbitrary types. Given the following class:

class Foo<T> {
    ...
    T value;
}

I have already overridden the equals method using Objects.deepEquals to compare the value fields. Is there an easy way to do the same with hashCode? Some utility method in guava or apache commons (i'm already using them for other things) ?

Unfortunately Objects.hash(field1, ... , value) does not work when value is an array.

I know one option is to do

Arrays.deepHashCode(new Object[]{ field1, ... , value });

but it feels wrong to create a new array for that instead of just looping it


Solution

  • HashCodeBuilder.reflectionHashCode(object) in commons-lang3.

    https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html