DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Merge Multiple PDFs in MuleSoft
  • Scaling Java Microservices to Extreme Performance Using NCache
  • Advanced Brain-Computer Interfaces With Java

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • A Modern Stack for Building Scalable Systems
  1. DZone
  2. Data Engineering
  3. Data
  4. Java 8 HashMaps, Keys, and the Comparable Interface

Java 8 HashMaps, Keys, and the Comparable Interface

In this post, we are going to discover a new, important feature that Java 8 brings to us in the event of hash collisions.

By 
Tamás Györfi user avatar
Tamás Györfi
·
May. 18, 16 · Tutorial
Likes (41)
Comment
Save
Tweet
Share
36.0K Views

Join the DZone community and get the full member experience.

Join For Free

Java 8 is coming with a lot of improvements and enhancements compared to the previous version. There are many classes that have been updated. HashMap—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 the event of hash collisions.

First of all, what is the easiest way to create collisions in a HashMap? First, 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 a case. Often 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 bucket in some kind of data structure (Note that in this case the overall performance of the map will degrade, as both insertions and retrievals will take longer to complete). 

To begin with, let's write a small application to simulate 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, 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—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 threshold (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 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 it 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, as there are no extra method calls needed for. It's worth mentioning that the same tieBreakOrder method is used when two Comparable keys turn out to be equal according to the compareTo method (the method returns 0).

In short, using Java 8 HashMaps buckets with too many entries will be tree-ified 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 big difference, but I hope now it's a bit more clear how HashMaps work internally.

Data structure Java (programming language) Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Merge Multiple PDFs in MuleSoft
  • Scaling Java Microservices to Extreme Performance Using NCache
  • Advanced Brain-Computer Interfaces With Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!