Java Reference
In-Depth Information
Whenever you use a hash set, you need to make sure that an appropriate hash function
exists for the type of the objects that you add to the set. Check the
equals
method
of your class. It tells you when two objects are considered equal. There are two
possibilities. Either
equals
has been defined or it has not been defined. If
equals
has not been defined, only identical objects are considered equal. In that case, don't
define
hashCode
either. However, if the
equals
method has been defined, look at
its implementation. Typically, two objects are considered equal if some or all of the
instance fields are equal. Sometimes, not all instance fields are used in the
comparison. Two
Student
objects may be considered equal if their
studentID
fields are equal. Define the
hashCode
method to combine the hash codes of the
fields that are compared in the
equals
method.
In a hash map, only the keys are hashed.
When you use a
HashMap
, only the keys are hashed. They need compatible
hashCode
and
equals
methods. The values are never hashed or compared. The
reason is simpleČthe map only needs to find, add, and remove keys quickly.
What can you do if the objects of your class have
equals
and
hashCode
methods
defined that don't work for your situation, or if you don't want to define an
appropriate
hashCode
method? Maybe you can use a
TreeSet
or
TreeMap
instead. Trees are the subject of the next section.
ch16/hashcode/Coin.java
1 /**
2
A coin with a monetary value.
3 */
4
public class
Coin
5 {
6 /**
7
Constructs a coin.
8 @param aValue
the monetary value of the coin
9 @param aName
the name of the coin
10 */
11
public
Coin(
double
aValue, String aName)
12 {