Search code examples
javahashcode

Generic hash codes in Java


I am somewhat new to Java. Is there is a hashcode utility class that can generate a good hash code for a generic object with members of arbitrary types inside the class? Can I recursively step through the instance of a generic java object and accumulate a hash code that guarantees two equal objects of this class will always compute the same hash code? The context of this question is Android and the Objects.hashCode() etc is not available to me in the Java version I am using (and I have no option to migrate to a newer version). I am guessing the answer is no based on what I have seen so far.


Solution

  • You could try the HashCodeBuilder from Apache Commons Lang. It's able to generate a hash code reflectively as follows:

    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }