public int hashCode() { return iMonth; }
final Date tNoelDate = new Date(2000, 12, 25); final int tValue = tNoelDate.hashCode();will assign the value 12 to tValue.
For example, suppose we want to store the dates when various composers died:
Bach | 1750-08-28 |
Beethoven | 1827-03-26 |
Cage | 1992-08-12 |
Chopin | 1849-10-17 |
Copland | 1990-12-02 |
Elgar | 1934-02-23 |
Handel | 1759-04-14 |
Mendelssohn | 1847-11-04 |
Purcell | 1695-11-21 |
Sibelius | 1957-09-20 |
Stanford | 1924-03-29 |
Tallis | 1585-11-23 |
Tchaikovsky | 1893-11-06 |
Vaughan-Williams | 1958-08-26 |
Walton | 1983-03-08 |
Suppose we add each of these dates to a HashSet, e.g. for Bach:
Date tDeathOfBach = new Date(1750, 8, 28); tHashSet.add(tDeathOfBach);
HashSet's add method uses Date's hashCode function, and so the values will be stored in 12 buckets:
Then, when later we ask the collection object whether it has the value 1893-11-06 (the date when Tchaikovsky died), the contains method can call hashCode on this value and, because this produces the value 11, the contains method only checks the values in the 11th bucket. The code of the contains method uses equals on each of these values in turn returning the value true if and only if it finds the value (in this case, the value 1893-11-06).