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:
It is repeatable:
hashCode(x)must return the sameintwhen called again unless set methods have been called.It is symmetric: if
x.equals(y), thenx.hashCode( )must ==y.hashCode( ), i.e., either both return true, or both return false.If
!x.equals(y), it is not required thatx.hashCode( )!=y.hashCode( ), but doing so may improve performance of hash tables, i.e., hashes may callhashCode( )beforeequals( ).
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 ...