Overriding the Hashcode Method

Problem

You want to use your objects in a hash, and you need to write a hashCode( ).

Discussion

The hashCode() method is supposed to return an int that should uniquely identify different objects.

A properly written hashCode( ) method will follow these rules:

  1. It is repeatable: hashCode(x) must return the same int when called again unless set methods have been called.

  2. It is symmetric: if x.equals(y), then x.hashCode( ) must == y.hashCode( ), i.e., either both return true, or both return false.

  3. If !x.equals(y), it is not required that x.hashCode( ) != y.hashCode( ), but doing so may improve performance of hash tables, i.e., hashes may call hashCode( ) before equals( ).

The default hashCode( ) on Sun’s JDK returns a machine address, which conforms to Rule 1. Conformance to Rules 2 and 3 depends, in part, upon your equals( ) method. Here is a program that prints the hashcodes of a small handful of objects:

/** Display hashCodes from some objects */
public class PrintHashCodes {

    /** Some objects to hashCode(  ) on */
    protected static Object[] data = {
        new PrintHashCodes(  ),
        new java.awt.Color(0x44, 0x88, 0xcc),
        new SomeClass(  )
    };

    public static void main(String[] args) {
        System.out.println("About to hashCode " + data.length + " objects.");
        for (int i=0; i<data.length; i++) {
            System.out.println(data[i].toString(  ) + " --> " + 
                data[i].hashCode(  ));
        }
        System.out.println("All done.");
    }
}

What does it print?

> jikes +E -d . PrintHashCodes.java > java PrintHashCodes About ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.