Java Reference
In-Depth Information
If your class is mutable, you should not be using objects of your class as keys in hash-based collections. If the
object has been used as a key changes after their use, you will not be able to locate the object in the collection because
locating an object in a hash based collection is based on its hash code. In such cases, you will have stranded objects in
the collection.
How should you implement a hashCode() method for a class? Here are some guidelines to write the logic for the
hashCode() method for your class, which is reasonable for most of the purposes:
Start with a prime number, say 37.
int hash = 37;
Compute the hash code value for each instance variable of primitive data types separately
using the following logic. Note that you need to use only those instance variables in the hash
code computation, which are also part of the equals() method logic. Let's store the result of
this step in an int variable code . Let's assume that value is the name of the instance variable.
For byte , short , int , and char data types, use their integer value as
code = (int)value;
For long data type, use the XOR for two halves of 64-bit as
code = (int)(value ^ (value >>>32));
For float data type, convert its floating-point values to an equivalent integer value using
code = Float.floatToIntBits(value)
For double data type, convert its floating-point value to long using the doubleToLongBits()
method of the Double class and then convert the long value to an int value using the
procedure as described above for the long data type.
long longBits = Double.doubleToLongBits(value);
code = (int)(longBits ^ (longBits >>>32));
For boolean data type, use 1 for true and 0 for false .
code = (value ? 1 : 0)
null . Otherwise, call its hashCode() method to
get its hash code. Suppose ref is the name of the reference variable.
For a reference instance variable, use 0 if it is
code = (ref == null ? 0: ref.hashCode());
Compute the hash code using the following formula. Using 59 in the formula is an arbitrary
decision. Any other prime number, say 47, will work fine.
hash = hash * 59 + code;
hashCode()
Repeat the above three steps for all instance variables you want to include in your
computation.
hash variable from your hashCode() method.
Finally, return the value contained in the
 
Search WWH ::




Custom Search