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).
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.