Java Reference
In-Depth Information
For your own classes, you should make up a hash code that combines the hash codes
of the instance fields in a similar way. For example, let us define a hashCode
method for the Coin class. There are two instance fields: the coin name and the coin
value. First, compute their hash code. You know how to compute the hash code of a
string. To compute the hash code of a floating-point number, first wrap the
floating-point number into a Double object, and then compute its hash code.
Define hashCode methods for your own classes by combining the hash codes for
the instance variables.
class Coin
{
public int hashCode()
{
int h1 = name.hashCode();
int h2 = new Double(value).hashCode();
. . .
}
}
715
716
Then combine the two hash codes.
final int HASH_MULTIPLIER = 29;
int h = HASH_MULTIPLIER * h1 + h2;
return h;
Use a prime number as the hash multiplierȌit scrambles the values better.
If you have more than two instance fields, then combine their hash codes as follows:
int h = HASH_MULTIPLIER * h1 + h2;
h = HASH_MULTIPLIER * h + h3;
h = HASH_MULTIPLIER * h + h4;
. . .
return h;
If one of the instance fields is an integer, just use the field value as its hash code.
When you add objects of your class into a hash table, you need to double-check that
the hashCode method is compatible with the equals method of your class. Two
objects that are equal must yield the same hash code:
Search WWH ::




Custom Search