Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.4k points)
edited by

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 (46k points)

HashMap: HashMap allows 0(1) lookup and addition. It is implemented by an array of associated lists.

Syntax:

public class HashMap extends AbstractMap 

implements Map, Cloneable, Serializable

  • A HashMap includes values based on the key.
  • It holds unique elements.
  • It may have one null key and many null values.
  • It has no order.

LinkedHashMap: LinkedHashMap gives 0(1) lookup and addition. Keys are commanded by their insertion position. It is executed by doubly-linked buckets.

Syntax:

public class LinkedHashMap extends HashMap 

0implements Map

  • A LinkedHashMap holds values based on the key.
  • It holds unique elements.
  • It may have one null key and many null values.
  • It is the same as HashMap rather than preserves the insertion order.

TreeMap: TreeMap gives O(log N) lookup and addition. Keys are commanded, so if you need to iterate over the keys in sorted order, you can. This means that keys need to implement the Comparable interface. TreeMap is executed by a Red-Black Tree.

Syntax:

public class TreeMap extends AbstractMap implements

NavigableMap, Cloneable, Serializable

  • A TreeMap holds values based on the key. It performs the NavigableMap interface and extends AbstractMap class.
  • It holds unique elements.
  • It can't have a null key but can have multiple null values.
  • It is the same as HashMap rather maintains ascending order(Sorted using the original order of its key).

Related questions

0 votes
2 answers
asked Jul 12, 2019 in Java by Aditya98 (1.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...