Difference between HashMap and LinkedHashMap in Java - TongtongLan/Java GitHub Wiki
HashMap和LinkedHashMap是Java中最常用的两个Map实现。 HashMap和LinkedHashMap之间的主要区别在于LinkedHashMap维护键的插入顺序,其中键被插入到LinkedHashMap中。另一方面,HashMap不保留任何顺序或键或值。在性能方面,HashMap和LinkedHashMap之间没有太大的区别,但是LinkedHashMap比HashMap有更多的内存足迹来维护双重的LinkedList,它用来跟踪键的插入顺序。有一段时间你注意到HashMap也按顺序返回元素在Java 8之前,当你使用Integer键,然后迭代Map时,你会看到它以特定的顺序返回条目,但这些不能保证。任何依赖于HashMap提供的顺序的代码在这些行为发生变化时将有可能在未来的版本中被破坏。
LinkedHashMap and HashMap in Java - Similarities
-
Both LinkedHashMap and HashMap are not synchronized and subject to race condition if shared between multiple threads without proper synchronization. Use Collections.synchronizedMap() for making them synchronized.
-
Iterator returned by HashMap and LinkedHashMap are fail-fast in nature.
-
Performance of HashMap and LinkedHashMap are similar also.
Difference between LinkedHashMap and HashMap in Java
-
First and foremost difference between LinkedHashMap and HashMap is order, HashMap doesn't maintain any order while LinkedHashMap maintains insertion order of elements in Java.
-
LinkedHashMap also requires more memory than HashMap because of this ordering feature. As I said before LinkedHashMap uses doubly LinkedList to keep order of elements.
-
LinkedHashMap actually extends HashMap and implements Map interface.
Few things to note, while using LinkedHashMap in Java
-
Default ordering provided by LinkedHashMap is the order on which key is inserted, known as insertion order, but LinkedHashMap can be created with another ordering called access order, which is defined by accessing entries.
-
重新输入映射,不会改变LinkedHashMap的插入顺序。
For example, if you already have mapping for a key, and want to update it's value by calling put(key, newValue), insertion order of LinkedHashMap will remain same.
-
Access order is affected by calling get(key), put(key, value) or putAll(). When a particular entry is accessed, it moves towards end of the doubly linked list, maintained by LinkedHashMap.
-
LinkedHashMap可以用来在Java中创建LRU缓存。
Since in LRU or Least Recently Used Cache, oldest non accessed entry is removed, which is the head of the doubly linked list maintained by LinkedHashMap.
-
Iterator of LinkedHashMap returns elements in the order e.g. either insertion order or access order.
-
LinkedHashMap also provides a method called removeEldestEntry(), which is protected and default implementation return false. If overridden, an implementation can return true to remove oldest entry, when a new entry is added.
Read more: http://www.java67.com/2012/08/difference-between-hashmap-and-LinkedHashMap-Java.html#ixzz518EIfjGL