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 same
int
when called again unless set methods have been
called.
It is symmetric:
if x.equals(y)
, then x.hashCode( )
must == y.hashCode( )
, i.e., either
both return true, or both return false.
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:
(r<<24 + g<<16 + b<<8 + alpha)
The “high bit” in this word having been set by shifting causes the value to appear negative when printed as a signed integer. Hashcode values are allowed to be negative.
3.146.34.146