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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

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

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

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

Related

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • How to Implement Linked Lists in Go
  • Recursive Feature Elimination in Practice
  • Text Clustering With Deepseek Reasoning

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  1. DZone
  2. Data Engineering
  3. Data
  4. HashMap vs. TreeMap vs. HashTable vs. LinkedHashMap

HashMap vs. TreeMap vs. HashTable vs. LinkedHashMap

Learn all about important data structures like HashMap, HashTable, and TreeMap.

By 
Ryan Wang user avatar
Ryan Wang
·
Mar. 28, 13 · Analysis
Likes (13)
Comment
Save
Tweet
Share
435.9K Views

Join the DZone community and get the full member experience.

Join For Free

map

Learn all about important data structures like HashMap, HashTable, and TreeMap.

Map is an important data structure. In this article, let's play with dogs and see how maps can be helpful in development.  

Map Overview

There are four . commonly used implementations of Map in Java SE: HashMap, TreeMap, Hashtable, and LinkedHashMap. If we use one sentence to describe each implementation, it would be the following:   

  •  HashMapis implemented as a hash table, and there is no ordering on keys or values. 
  •  TreeMap is implemented based on red-black tree structure, and it is ordered by the key. 
  •  LinkedHashMap preserves the insertion order
  •  Hashtable  is synchronized in contrast to HashMap. 

This gives us the reason that HashMap should be used if it is thread-safe since Hashtable has overhead for synchronization. 

HashMap 

If the key of the HashMap is self-defined objects, then equals() and hashCode() contract need to be followed. 

class Dog {
String color;

Dog(String c) {
color = c;
}
public String toString(){
return color + " dog";
}
}

public class TestHashMap {
public static void main(String[] args) {
HashMap hashMap = new HashMap();
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");

hashMap.put(d1, 10);
hashMap.put(d2, 15);
hashMap.put(d3, 5);
hashMap.put(d4, 20);

//print size
System.out.println(hashMap.size());

//loop HashMap
for (Entry entry : hashMap.entrySet()) {
System.out.println(entry.getKey().toString() + " - " + entry.getValue());
}
}
}


Output:

white dog – 5
black dog – 15
red dog – 10
white dog – 20


Note here: We add "white dogs" twice by mistake, but the HashMap takes it. This does not make sense, because now we are confused how many white dogs are really there.  The Dog class should be defined as follows:

class Dog {
String color;

Dog(String c) {
color = c;
}

public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}

public int hashCode() {
return color.length();
}

public String toString(){
return color + " dog";
}
}


Now the output is:

red dog – 10
white dog – 20
black dog – 15


The reason is that HashMap doesn't allow two identical elements. By default, the hashCode() and equals() methods implemented in Object class are used. The default hashCode()  method gives distinct integers for distinct objects, and the equals() method only returns true when two references refer to the same object.

Check out the hashCode() and equals() contract if this is not obvious to you. 

TreeMap

A TreeMap is sorted by keys. Let's first take a look at the following example to understand the "sorted by keys" idea. 

class Dog {
String color;

Dog(String c) {
color = c;
}
public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}

public int hashCode() {
return color.length();
}
public String toString(){
return color + " dog";
}
}


public class TestTreeMap {
public static void main(String[] args) {
Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");

TreeMap treeMap = new TreeMap();
treeMap.put(d1, 10);
treeMap.put(d2, 15);
treeMap.put(d3, 5);
treeMap.put(d4, 20);

for (Entry entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}


Output:

Exception in thread “main” java.lang.ClassCastException: collection.Dog cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(Unknown Source)
at collection.TestHashMap.main(TestHashMap.java:35)

Since TreeMaps are sorted by keys, the object for key has to be able to compare with each other, that's why it has to implement Comparable interface. For example,  you use String as key, because String implements Comparable interface.  Let's change the Dog, and make it comparable.  

class Dog implements Comparable{
String color;
int size;

Dog(String c, int s) {
color = c;
size = s;
}

public String toString(){
return color + " dog";
}

@Override
public int compareTo(Dog o) {
return  o.size - this.size;
}
}

public class TestTreeMap {
public static void main(String[] args) {
Dog d1 = new Dog("red", 30);
Dog d2 = new Dog("black", 20);
Dog d3 = new Dog("white", 10);
Dog d4 = new Dog("white", 10);

TreeMap treeMap = new TreeMap();
treeMap.put(d1, 10);
treeMap.put(d2, 15);
treeMap.put(d3, 5);
treeMap.put(d4, 20);

for (Entry entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}


Output:

red dog – 10
black dog – 15
white dog – 20


It is sorted by key, i.e., dog size in this case.  If "Dog d4 = new Dog("white", 10);" is replaced with "Dog d4 = new Dog("white", 40);", the output would be: 

white dog – 20
red dog – 10
black dog – 15
white dog – 5


The reason is that TreeMap now uses the compareTo()  method to compare keys. Different sizes make different dogs!  

Hashtable

From Java Doc: "The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. 

LinkedHashMap 

LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.  Let's replace the HashMap with LinkedHashMap using the same code used for HashMap. 

class Dog {
String color;

Dog(String c) {
color = c;
}

public boolean equals(Object o) {
return ((Dog) o).color == this.color;
}

public int hashCode() {
return color.length();
}

public String toString(){
return color + " dog";
}
}

public class TestHashMap {
public static void main(String[] args) {

Dog d1 = new Dog("red");
Dog d2 = new Dog("black");
Dog d3 = new Dog("white");
Dog d4 = new Dog("white");

LinkedHashMap linkedHashMap = new LinkedHashMap();
linkedHashMap.put(d1, 10);
linkedHashMap.put(d2, 15);
linkedHashMap.put(d3, 5);
linkedHashMap.put(d4, 20);

for (Entry entry : linkedHashMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}


Output:

red dog – 10
black dog – 15
white dog – 20



The difference is that if we use HashMap the output could be the following: the insertion order is not preserved.

red dog – 10
white dog – 20
black dog – 15



If you enjoyed this article and want to learn more about Java Collections, check out this collection of tutorials and articles on all things Java Collections.

Data structure

Published at DZone with permission of Ryan Wang. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • How to Implement Linked Lists in Go
  • Recursive Feature Elimination in Practice
  • Text Clustering With Deepseek Reasoning

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!