Will Clausen's Website

Categories
WCW

Effective Java: Item #9

Header: I am working my way through effective java and am writing these posts to help solidify my understanding of what’s in the book. This is the first post of it’s kind, but I’m sure I’ll get around to writing posts on the previous 8 items, along with the next 45-ish.

Effective Java: Item #9, Always override .hashcode() when overriding .equals()

This item builds off of the last one, which discussed things that must be considered when overriding the .equals() function for a class.

When .equals() is overridden, you absolutely¬†mustoverride .hashcode(). If you don’t you will not be able to use hashmaps with instances of your class. This would suck, as hashmaps can help make many important operations¬†run in linear instead of quadratic time.

So, it’s necessary to override .hashcode() when overriding .equals(). What now? How do we do that? The key is to use the member variables for the class, so that classes with equal data members have equal hash codes.

This item provides some simple tips to create a worthwhile hash function using the type/value of the member variables in a class.

For each field, f, in the class compute a value (int) c, where:

  1. If f is a boolean, c = ( f && 1);
  2. If f is an int, c = f;
  3. if f is a long, c = (int) (f ^ (f >>> 32));
  4. If f is a float, c = Float.floatToIntBits(f);
  5. If f is a double c = Double.doubleToLongBits(f);
  6. If the field is a reference to another object, recursively invoke .hashcode() on it, or compute a “canonical representation” for the field and invoke .hashcode() on that.

Next, combine c into a non-zero result variable by result = 31 * result + c, and do this for each c corresponding to the fields f

Finally, test whether the function actually produces equal hashcodes for equal objects.

Additionally, you may need to consider the performance of your .hashcode() implementation, and if it is too slow, improve the performance by either caching the hash code in the object at construction, or lazily instantiate the hash code.

DONE!

 

Leave a Reply

Your email address will not be published. Required fields are marked *