javalinkedhashmapsortedmap

Why does LinkedHashMap not implement SortedMap?


LinkedHashMap is clearly an ordered Map. It orders based upon insertion.

So why does it not implement SortedMap?


Solution

  • From the LinkedHashMap Javadocs:

    Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

    While SortedMap is:

    A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time.

    So both exist for different purposes. LinkedHashMap provides iteration in the same order of key insertion while SortedMap is for sorting using Comparator or Comparable.