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-
onsontheobjectismodified.Thisintegerneednotremainconsistentfromone
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
ofthetwoobjectsmustproducedistinctintegerresults.However,theprogram-
mershouldbeawarethatproducingdistinctintegerresultsforunequalobjects
might improve the performance of hash tables.
Failtoobeythiscontractandyourclass'sinstanceswillnotworkproperlywithJava's
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:
java.util.Map<Point,
String>
map
=
new
java.util.HashMap<>();
map.put(p1, "first point");
System.out.println(map.get(p1)); // Output: first point
System.out.println(map.get(new Point(10, 20))); // Output:
null
Search WWH ::




Custom Search