Java Reference
In-Depth Information
Output
hash code of coin1=Ċ1513525892
hash code of coin2=Ċ1513525892
hash code of coin3=Ċ1768365211
Coin[value=0.25,name=quarter]
Coin[value=0.05,name=nickel]
S ELF C HECK
7. What is the hash code of the string ÐtoÑ ?
8. What is the hash code of new Integer(13) ?
C OMMON E RROR 16.1: Forgetting to Define hashCode
When putting elements into a hash table, make sure that the hashCode method is
defined. (The only exception is that you don't need to define hashCode if
equals isn't defined. In that case, distinct objects of your class are considered
different, even if they have matching contents.)
If you forget to implement the hashCode method, then you inherit the
hashCode method of the Object class. That method computes a hash code of
the memory location of the object. For example, suppose that you do not define the
hashCode method of the Coin class. Then the following code is likely to fail:
Set<Coin> coins = new HashSet<Coin>();
coins.add(new Coin(0.25, ÐquarterÑ));
// The following comparison will probably fail if hashCode not defined
if (coins.contains(new Coin(0.25, ÐquarterÑ))
System.out.println(ÐThe set contains a
quarter.Ñ);
The two Coin objects are constructed at different memory locations, so the
hashCode method of the Object class will probably compute different hash
codes for them. (As always with hash codes, there is a small chance that the hash
codes happen to collide.) Then the contains method will inspect the wrong
bucket and never find the matching coin.
Search WWH ::




Custom Search