Schlagwort: HashCode

Why to only use immutable variables for Java hashCode()

There are lots of websites which explain to Java coders, that whenever you override equals() you also have to override hashCode(). You need to override those methods especially when you use JPA. Eclipse is a nice tool, that helps you with generating those „custom implementations“.

But beware of the such generated hashCode() methods. It will ruine your day when you use HashSet or HashTable containers and expect them to work like they did with the standard implementation.

The rule of thumb is:

„Only include those variables in the hashCode generation, which will not change during the usage time of the object.“

Why? Just think about a simple class „Foo“ that has a mutable (means normal) property named „value“ and a Eclipse generated hashCode() method implementation (which will use the field value to calculate the hash). Given this class, what will this little test print out?:

    public static void main(String[] args) {
        Foo f = new Foo();
        f.value = 100;
        HashSet<Foo> set = new HashSet<Foo>();
        f.value = 101;
        if (set.contains(f)){
            System.out.println("All fine!");
        } else {

The right answer is: „WTF!?“

Believe it or not, the HashSet will not recognise the instance f anymore, because HashSet and HashTable will use the hashCode() method before the equals() method will be used to identify if an object is included in the container.

So only use immutable variables like ids that will not change during the usage of the class. Such a hashCode() method will still comply to the contract that

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.