Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata