Effective Java! Obey the `hashCode` contract

Kyle Carter
3 min readJan 10, 2021

Today’s topic goes right in line with last week’s. This week we are talking about the hashCode function. Just like the equals function we talked about last week this method also has a contract that should be followed albeit a simpler one. As is the signature, taking no parameters and return an integer. So lets get to the contract:

  • Given no changes to an object the value returned from the function should remain the same.
  • If two objects are effectively equals their hashcodes must be the same.
  • (This one is more of a non-requirement) Given two objects that are effectively unequal they need not have different hash code values.

So as you can see the contract of hashcode is very tied into equality. The requirement that gets broken the most is the second requirement. If you don't implement a hash code function two effectively equivalent objects will likely not have the same value returned by the function. So let's look at an example:

Map<Address, String> addressBook = new HashMap<>();
addressBook.put(new Address("123","Foggy Lane" "Made Up City", "USA"), "James");
addressBook.get(new Address("123","Foggy Lane" "Made Up City", "USA"));

Given the above example the expectation would be that line three would return “James” however, if the hash code function is not written properly, it will instead return null.

So let’s write the simplest hashcode function that is legal:

@Override
public int hashCode() {
return 42;
}

Yes, that is a totally valid hashcode function per the contract. It always returns the same thing if called multiple times on the same object, it returns the same value for functionally equivalent objects, and it’s OK that it returns the same hashcode for two objects that are not functionally equivalent. However, even though it meets the contract, not having some variety to the values returned is a horrible idea and can lead to a great decrease in performance. For example, the above hashcode function would effectively turn a HashMap into a linked list as far as performance goes.

There must be a better way, and there is. Effective Java gives us a recipe we can follow to create a solid hashcode function.

  1. Declare an int named result and initialize it to the value of the first significant field of the object (reminder of what "significant field" means is a field…
Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.