Differences between hashmap and Treemap
Certainly! Let’s compare HashMap and TreeMap in Java, highlighting their differences in a tabular form. I’ll provide explanations and Java examples for each difference:
Feature | HashMap | TreeMap |
Synchronization | Not synchronized (non-thread-safe) | Synchronized (thread-safe) |
Null Keys and Values | Allows null keys and multiple null values | Doesn’t allow null keys but allows null values (throws NullPointerException) |
Performance | Generally faster due to lack of synchronization | Slower due to synchronization overhead |
Ordering | No specific order of key-value pairs | Sorted by keys (natural order or custom comparator) |
Introduced Version | Introduced in Java 1.2 | Introduced in Java 1.2 |
Legacy Status | Non-legacy (modern) | Legacy (older) |
Table of Contents
Example
Now, let’s illustrate these differences with examples:
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
public class HashMapVsTreeMap {
public static void main(String[] args) {
// Example using HashMap
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(100, "Alice");
hashMap.put(104, "Bob");
hashMap.put(101, "Charlie");
hashMap.put(102, "David");
System.out.println("-----------HashMap-----------");
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
// Example using TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(100, "Alice");
treeMap.put(104, "Bob");
treeMap.put(101, "Charlie");
treeMap.put(102, "David");
System.out.println("-----------TreeMap-----------");
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Output:
———–HashMap———–
100 Alice
101 Charlie
102 David
104 Bob
———–TreeMap———–
100 Alice
101 Charlie
102 David
104 Bob
Remember that HashMap provides fast access but doesn’t guarantee order, while TreeMap maintains sorted order based on keys.