Java Reference
In-Depth Information
Note A resurrected object's finalizer cannot be called again.
Hash Codes
The hashCode() method returns a 32-bit integer that identifies the current object's
hash code ,asmallvaluethatresultsfromapplyingamathematicalfunctiontoapoten-
tially large amount of data. The calculation of this value is known as hashing .
You must override hashCode() when overriding equals() , and in accordance
with the following contract, which is specified in hashCode() 's Java documentation:
• Wheneveritisinvokedonthesameobjectmorethanonceduringanexecution
of a Java application, the hashCode() method must consistently return the
sameinteger,providednoinformation usedin equals(Object) comparis-
execution of an application to another execution of the same application.
• If two objects are equal according to the equals(Object) method, then
callingthe hashCode() methodoneachofthetwoobjectsmustproducethe
same integer result.
• It is not required that if two objects are unequal according to the
equals(Object) method, then calling the hashCode() method on each
might improve the performance of hash tables.
hash-based Collections Framework classes, such as java.util.HashMap . (I will
discuss HashMap and other Collections Framework classes in Chapter 5 .)
Ifyouoverride equals() butnot hashCode() ,youmostimportantlyviolatethe
second item in the contract: The hash codes of equal objects must also be equal. This
violation can lead to serious consequences, as demonstrated in the following example:
map.put(p1, "first point");
System.out.println(map.get(p1)); // Output: first point
System.out.println(map.get(new Point(10, 20))); // Output:
Search WWH ::

Custom Search