Difference between HashMap, LinkedHashMap and TreeMap

后端 未结 17 2114
醉话见心
醉话见心 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
    • HashMap:

      • Order not maintains
      • Faster than LinkedHashMap
      • Used for store heap of objects
    • LinkedHashMap:

      • LinkedHashMap insertion order will be maintained
      • Slower than HashMap and faster than TreeMap
      • If you want to maintain an insertion order use this.
    • TreeMap:

      • TreeMap is a tree-based mapping
      • TreeMap will follow the natural ordering of key
      • Slower than HashMap and LinkedHashMap
      • Use TreeMap when you need to maintain natural(default) ordering
    0 讨论(0)
  • 2020-11-22 01:40

    I prefer visual presentation:

    ╔══════════════╦═════════════════════╦═══════════════════╦═════════════════════╗
    ║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap   ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║ Iteration    ║  no guarantee order ║ sorted according  ║                     ║
    ║   Order      ║ will remain constant║ to the natural    ║    insertion-order  ║
    ║              ║      over time      ║    ordering       ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║  Get/put     ║                     ║                   ║                     ║
    ║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)        ║
    ║ containsKey  ║                     ║                   ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║              ║                     ║   NavigableMap    ║                     ║
    ║  Interfaces  ║         Map         ║       Map         ║         Map         ║
    ║              ║                     ║    SortedMap      ║                     ║
    ╠══════════════╬═════════════════════╬═══════════════════╬═════════════════════╣
    ║              ║                     ║                   ║                     ║
    ║     Null     ║       allowed       ║    only values    ║       allowed       ║
    ║ values/keys  ║                     ║                   ║                     ║
    ╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣
    ║              ║   Fail-fast behavior of an iterator cannot be guaranteed      ║
    ║   Fail-fast  ║ impossible to make any hard guarantees in the presence of     ║
    ║   behavior   ║           unsynchronized concurrent modification              ║
    ╠══════════════╬═════════════════════╦═══════════════════╦═════════════════════╣
    ║              ║                     ║                   ║                     ║
    ║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked    ║
    ║              ║                     ║                   ║       buckets       ║
    ╠══════════════╬═════════════════════╩═══════════════════╩═════════════════════╣
    ║      Is      ║                                                               ║
    ║ synchronized ║              implementation is not synchronized               ║
    ╚══════════════╩═══════════════════════════════════════════════════════════════╝
    
    0 讨论(0)
  • 2020-11-22 01:40

    The most important among all the three is how they save the order of the entries.

    HashMap - Does not save the order of the entries. eg.

    public static void main(String[] args){
            HashMap<String,Integer> hashMap = new HashMap<>();
            hashMap.put("First",1);// First ---> 1 is put first in the map
            hashMap.put("Second",2);//Second ---> 2 is put second in the map
            hashMap.put("Third",3); // Third--->3 is put third in the map
            for(Map.Entry<String,Integer> entry : hashMap.entrySet())
            {
                System.out.println(entry.getKey()+"--->"+entry.getValue());
            }
        }
    

    LinkedHashMap : It save the order in which entries were made. eg:

    public static void main(String[] args){
            LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("First",1);// First ---> 1 is put first in the map
            linkedHashMap.put("Second",2);//Second ---> 2 is put second in the map
            linkedHashMap.put("Third",3); // Third--->3 is put third in the map
            for(Map.Entry<String,Integer> entry : linkedHashMap.entrySet())
            {
                System.out.println(entry.getKey()+"--->"+entry.getValue());
            }
        }
    

    TreeMap : It saves the entries in ascending order of the keys. eg:

    public static void main(String[] args) throws IOException {
            TreeMap<String,Integer> treeMap = new TreeMap<>();
            treeMap.put("A",1);// A---> 1 is put first in the map
            treeMap.put("C",2);//C---> 2 is put second in the map
            treeMap.put("B",3); //B--->3 is put third in the map
            for(Map.Entry<String,Integer> entry : treeMap.entrySet())
            {
                System.out.println(entry.getKey()+"--->"+entry.getValue());
            }
        }
    

    0 讨论(0)
  • 2020-11-22 01:44

    All three classes implement the Map interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:

    • HashMap makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.
    • TreeMap will iterate according to the "natural ordering" of the keys according to their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap interface, which contains methods that depend on this sort order.
    • LinkedHashMap will iterate in the order in which the entries were put into the map

    "Hashtable" is the generic name for hash-based maps. In the context of the Java API, Hashtable is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Use ConcurrentHashMap instead of Hashtable.

    0 讨论(0)
  • 2020-11-22 01:46

    Following are major difference between HashMap and TreeMap

    1. HashMap does not maintain any order. In other words , HashMap does not provide any guarantee that the element inserted first will be printed first, where as Just like TreeSet , TreeMap elements are also sorted according to the natural ordering of its elements

    2. Internal HashMap implementation use Hashing and TreeMap internally uses Red-Black tree implementation.

    3. HashMap can store one null key and many null values.TreeMap can not contain null keys but may contain many null values.

    4. HashMap take constant time performance for the basic operations like get and put i.e O(1).According to Oracle docs , TreeMap provides guaranteed log(n) time cost for the get and put method.

    5. HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.

    6. HashMap uses equals() method in comparison while TreeMap uses compareTo() method for maintaining ordering.

    7. HashMap implements Map interface while TreeMap implements NavigableMap interface.

    0 讨论(0)
提交回复
热议问题