Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Java by (920 points)

What is the difference between HashMap, LinkedHashMap and TreeMap in Java? I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet()); 
print(m1.values()); 

SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet()); 
print(sm.values());

LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet()); 
print(lm.values());

1 Answer

0 votes
by (13.2k points)

All three classes implement the same java.util.map interface and mostly have the same functionality. But here are their functionalities-

HashMap

  • HashMap is equipped with the complexity of O(1) for insertion and lookup.

  • It allows only one null key but multiple null values.

  • It does not maintain any order.

TreeMap

  • TreeMap is equipped with complexity of O(logN).

  • It doesn’t allow null key but allows multiple null values.

  • It does maintain order.

LinkedHashMap

  • LinkedHashMap is having complexity of O(1) for insertion and lookup.

  • In contrast to others it allows one null key and multiple null values.

  • It maintains order in which key-value pairs are inserted.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Krishna (2.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...