Difference between HashMap, LinkedHashMap and TreeMap

后端 未结 17 2151
醉话见心
醉话见心 2020-11-22 01:01

What is the difference between HashMap, LinkedHashMap and TreeMap in Java? I don\'t see any difference in the output as all the three

17条回答
  •  無奈伤痛
    2020-11-22 01:36

    All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map interface, and represents mapping from unique key to values.

    HashMap

    1. A HashMap contains values based on the key.

    2. It contains only unique elements.

    3. It may have one null key and multiple null values.

    4. It maintains no order.

      public class HashMap extends AbstractMap implements Map, Cloneable, Serializable

    LinkedHashMap

    1. A LinkedHashMap contains values based on the key.
    2. It contains only unique elements.
    3. It may have one null key and multiple null values.
    4. It is same as HashMap instead maintains insertion order. //See class deceleration below

      public class LinkedHashMap extends HashMap implements Map

    TreeMap

    1. A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
    2. It contains only unique elements.
    3. It cannot have null key but can have multiple null values.
    4. It is same as HashMap instead maintains ascending order(Sorted using the natural order of its key.).

      public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable

    Hashtable

    1. A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key.
    2. It contains only unique elements.
    3. It may have not have any null key or value.
    4. It is synchronized.
    5. It is a legacy class.

      public class Hashtable extends Dictionary implements Map, Cloneable, Serializable

    Ref: http://javarevisited.blogspot.in/2015/08/difference-between-HashMap-vs-TreeMap-vs-LinkedHashMap-Java.html

提交回复
热议问题