I'm wondering what is the best practice for writing #hashCode() method in java. Good description can be found here. Is it that good?
The idea is to make each cell of hash table point to a linked list of records that have same hash function value. Let's create a hash function, such that our hash table has 'N' number of buckets. To insert a node into the hash table, we need to find the hash index for the given key.
Probably the one most commonly used is SHA-256, which the National Institute of Standards and Technology (NIST) recommends using instead of MD5 or SHA-1. The SHA-256 algorithm returns hash value of 256-bits, or 64 hexadecimal digits.
We implement hashing through a function called hashCode in Java.
Here's a quote from Effective Java 2nd Edition, Item 9: "Always override hashCode
when you override equals
":
While the recipe in this item yields reasonably good hash functions, it does not yield state-of-the-art hash functions, nor do Java platform libraries provide such hash functions as of release 1.6. Writing such hash functions is a research topic, best left to mathematicians and computer scientists. [... Nonetheless,] the techniques described in this item should be adequate for most applications.
int
variable called result
int
hashcode c
for each field f
that defines equals
: boolean
, compute (f ? 1 : 0)
byte, char, short, int
, compute (int) f
long
, compute (int) (f ^ (f >>> 32))
float
, compute Float.floatToIntBits(f)
double
, compute Double.doubleToLongBits(f)
, then hash the resulting long
as in aboveequals
method compares the field by recursively invoking equals
, recursively invoke hashCode
on the field. If the value of the field is null
, return 0Arrays.hashCode
methods added in release 1.5c
into result
as follows: result = 31 * result + c;
Now, of course that recipe is rather complicated, but luckily, you don't have to reimplement it every time, thanks to java.util.Arrays.hashCode(Object[])
.
@Override public int hashCode() { return Arrays.hashCode(new Object[] { myInt, //auto-boxed myDouble, //auto-boxed myString, }); }
As of Java 7 there is a convenient varargs variant in java.util.Objects.hash(Object...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With