Java 8 Hashmaps, Keys and the Comparable Interface
A quick 101 for what to do in Java 8 in case of hash collisions.
Join the DZone community and get the full member experience.
Join For Free/**
* This post is intended to be a 101 quickie for the less experienced.
* It does not provide new or innovative ways of solving a certain problem,
* just summarizes a topic the way I see it.
*
**/
Java 8 is coming with a lot of improvements/enhancements compared to the previous version. There are pretty many classes that have been updated, HashMap—as one of the most used data structure—is no exception. In this post, we are going to discover a new, important feature that Java 8 brings to us in case of hash collisions.
First of all, what is the easiest way to create collisions in a HashMap? Of course, let’s create a class that has its hash function messed up in the worst way possible: a hashCode() implementation that returns a constant value. I usually ask people during technical interviews what happens in such case. Very many times the candidates think that the map will contain one and only one entry, as an older entry will always be overwritten by the newer one. That, of course, is not true. Hash collisions do not cause a HashMap to overwrite entries, that only happens if we try to put two entries with keys equal based on their equals() method. Entries with non-equal keys and the same hash code will end up in the same hash bucket in some kind of data structure. See below an example for Java 7:
To begin with, let’s write a small application to simulates those collisions. The demo application here is a bit exaggerated in the sense that it generates far more collisions than we’d normally have in a real-world application, but still, it’s important to prove a point.
In our example, we are going to use a Person object as keys in the map, while the values will be Strings. Let’s see the implementation for the Person object, with a first name, a last name, and an Id in the form of a UUID object:
public class Person {
private String firstName;
private String lastName;
private UUID id;
public Person(String firstName, String lastName, UUID id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
@Override
public int hashCode() {
return 5;
}
@Override
public boolean equals(Object obj) {
// ... pertty good equals here taking into account the id field...
}
}
And now let’s generate some collisions:
private static final int LIMIT = 500_000;
private void fillAndSearch() {
Person person = null;
Map<Person, String> map = new HashMap<>();
for (int i=0;i<LIMIT;i++) {
UUID randomUUID = UUID.randomUUID();
person = new Person("fn", "ln", randomUUID);
map.put(person, "comment" + i);
}
long start = System.currentTimeMillis();
map.get(person);
long stop = System.currentTimeMillis();
System.out.println(stop-start+" millis");
}
I ran this code on a pretty good machine, and it took 2.5 hours to complete, with the final search taking ~40 milliseconds. Now, without any prior explanation, let’s make a tiny change to our Person class: let’s make it implement Comparable<Person>, and add the following method:
@Override
public int compareTo(Person person) {
return this.id.compareTo(person.id);
}
Now, let’s run the map filler method one more time. On my machine, it completes in under 1 minute, with a final searching of zero milliseconds, aka we’ve made it 150 times faster!
As I mentioned, Java 8 comes with many improvements and that also affects HashMap. In Java 7, colliding entries were kept in a linked list inside the bucket. Starting from version 8, if the number of collisions is higher than a certain threshold (8), and the map’s capacity is larger than another trhreshold (64), the HashMap implementation will convert that linked list into a binary tree.
Aha! So in case of non-comparable keys the resulting tree is unbalanced, while in the other case it’s better balanced, right? Nope. The tree implementation inside the HashMap is a Red-Black tree, which means it will always be balanced. I even wrote a tiny reflection-based utility to see the height of the resulting trees. For 50.000 entries (I had no courage to let it run longer) both versions (with and without Comparable keys) yielded a tree height of 19.
Ok, then how come there’s such a big difference? When the HashMap implementation tries to find the location of a new entry in the tree, first checks whether the current and the new values are easily comparable (Comparable interface) or not. In the latter case, it has to fall back to a comparison method called tieBreakOrder(Object a, Object b). This method tries to compare the two object based on class name first, and then using System.identityHashCode. This is really tedious for 500.000 entries that we create in the test. However, when the key implements Comparable, the process is much simpler. The key itself defines how it compares to other keys, so the whole insertion/retrieval process speeds up. It’s worth mentioning that the same tieBreakOrder method is used in case when two Comparable keys turn out to be equal according to the compareTo method (aka the method returns 0).
In retrospective: using Java 8 HashMaps buckets with too many entries will be treefied once a threshold value is met. The resulting tree is a balanced Red-Black tree in which keys that implement Comparable can be inserted and/or removed much easier than non-comparable ones. Usually for buckets with not so many collisions this whole Comparable / not comparable stuff will make no practical difference, but I hope now it’s a bit more clear how HashMaps work internally.
Published at DZone with permission of Tamás Györfi, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Azure Virtual Machines
-
A Comprehensive Guide To Testing and Debugging AWS Lambda Functions
-
Introduction to API Gateway in Microservices Architecture
-
Understanding Data Compaction in 3 Minutes
Comments