Home  Collections intro  Lists  Maps  Sets  Which collection class?  Sorting  Hashing  Advanced
 Video lecture: hash tables  Bloom filters

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:

  • Write an equals() method that compares all the fields of the class on this object with those of the object passed in;
  • Write a hashCode() method which returns a hash code: an integer that can be used to "narrow down the search".

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).

comments powered by Disqus

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.