The Java collection class, java.util.HashMap
enables the storage of Key Value pairs. Given a Key, the HashMap enables the associated Value to be efficiently retrieved.
This tutorial, complete with an easy to understand UML visualization, explains how HashMap works.
To use the java.util.HashMap:
java.util.HashMap::put
– adds a Key Value pair to the Mapjava.util.HashMap::get
– retrieves the Value from the Map, given a Keyjava.lang.Object::hashCode
– overridden by custom key classes (see: PersonKey below), returns a number which should be as unique as possible for different keys. Note in the example below there are two different:PersonKey
Java objects. However they are the same key because they both contain “Bill Hanson”, and both should return the samehashCode
, and both should beequals
java.lang.Object::equals
– overridden by custom key classes (see: PersonKey below). The same key objects must be equals and must return the same hashCode. Different Keys e.g. Bill Hanson and Jack Johnson, must not be equals, and it is desirable that they return different hashCodes.
In the following example, a custom Key class, PersonKey,
provides custom hashCode
and equals
methods. Take 8 steps through the visualization, and read the associated code to get an understand how java.util.HashMap
works. At this point in time the visualization is best viewed in a desktop or tablet.
Attention: Click Here To Open Visualization Full Screen
Http iframes are not shown in https pages in many major browsers. Please read this post for details.
Why is a HashMap fast at retrieving Values?
A HashMap doesn’t need to iterate through all of its contained Keys to locate the correct Key. It uses the hashCode to quickly locate the correct element in the internal array, then returns the Value from the array.
What happens when different keys return the same hashCode?
Performance degrades, this topic is covered in my next blog post.
Do you like this Codelytics’ visualization?
If you like our visualizations, be sure to subscribe to our mailing list below. With your free subscription, we will periodically send you alerts about new tutorials and visualizations posted here.
What is your experience with HashMap?
What do you think about Hashmap? What do you think about this Codelytics’ visualization of Hashmap? We’d love to see your feedback in the comments below.
Leave a Reply