Making your classes work with Java HashMaps and HashSets
We mentioned previously that using a hash map is straightforward if the keys are of "ordinary" classes from the standard Java libraries (String, number wrappers such as Integer, Long, Point etc). These have generally already been written to be used as keys. For classes that you write from scratch that you wish to use as keys, then you will need to override two special methods.
The steps you need to take are as follows:
Actually writing the hashCode() and equals() methods is covered on a separate page of this tutorial as are an introduction to hash codes and some hash function guidelines (suggesting some things to put inside the hashCode() method).
Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved. If you have any feedback on the Java collections tutorials in this section or about the content of this site in general, please leave a message on the Javamex forum.