Recipe 9.3 Overriding the hashCode Method


Problem

You want to use your objects in a HashMap, HashSet, Hashtable, or other Collection, and you need to write a hashCode( ) method.

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 repeatedly, unless set methods have been called.

  2. It is consistent with equality: if x.equals(y), then x.hashCode( ) must == y.hashCode( ).

  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 to hashCode 3 objects. PrintHashCodes@982741a0 --> -1742257760 java.awt.Color[r=68,g=136,b=204] --> -12285748 SomeClass@860b41ad --> -2046082643 All done. >

The hashcode value for the Color object is interesting. It is actually computed as something like:

alpha<<24 + r<<16 + g<<8 + b

In this formula, r, g, and b are the red, green, and blue components respectively, and alpha is the transparency. Each of these quantities is stored in 8 bits of a 32-bit integer. If the alpha value is greater than 128, the "high bit" in this word having been set by shifting into the sign bit of the word causes the integer value to appear negative when printed as a signed integer. Hashcode values are of type int, so they are allowed to be negative.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net