Similarities between HashMap, LinkedHashMap, TreeMap

Similarities between HashMap, LinkedHashMap and TreeMap in Java

In this article

  • What HashMap, LinkedHashMap and TreeMap have in common
  • Shared Map interface behaviour
  • Unique keys and the Map contract
  • Common methods available on all three classes
  • Frequently asked questions about HashMap, LinkedHashMap and TreeMap

Frequently Asked Questions

What do HashMap, LinkedHashMap and TreeMap have in common?

All three are part of the Java Map family and implement the Map interface. They store data as key-value pairs, do not allow duplicate keys, and provide the common Map methods such as put(), get(), remove() and containsKey().

Do HashMap, LinkedHashMap and TreeMap allow duplicate keys?

No. As Map implementations, none of them allow duplicate keys. If you insert a value using a key that already exists, the previous value associated with that key is replaced.

Are HashMap, LinkedHashMap and TreeMap synchronized?

No, none of these three classes is synchronized by default. If you need thread-safe behaviour you should look at the concurrent collections or wrap the map using the appropriate utility method.

Which common methods are available on all three map classes?

Because they all implement the Map interface, methods such as put(), get(), remove(), containsKey(), keySet(), entrySet() and size() are available on HashMap, LinkedHashMap and TreeMap alike.

How do HashMap, LinkedHashMap and TreeMap differ from each other?

Although they share the Map contract, they differ in ordering and internal structure. HashMap does not guarantee any order, LinkedHashMap maintains insertion order, and TreeMap keeps its entries sorted. For a detailed comparison, see the related article on the difference between HashMap and TreeMap.

Leave a Comment