Member-only story

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:

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

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

No responses yet