源码分析——What is LinkedHashMap

Posted 喵喵7781

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了源码分析——What is LinkedHashMap相关的知识,希望对你有一定的参考价值。

  <p>Hash table and linked list implementation of the <tt>Map</tt> interface,  with predictable iteration order.  This implementation differs from  <tt>HashMap</tt> 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  (<i>insertion-order</i>).  Note that insertion order is not affected  if a key is <i>re-inserted</i> into the map.  (A key <tt>k</tt> is
  reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when  <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to  the invocation.)


 <p> <tt> Map </ tt>接口的哈希表和链表实现,有序。此实现与<tt> HashMap </ tt>的不同之处在于它维护了一个贯穿其entry数组的双向链表。此链接列表定义迭代排序,通常是插入顺序。请注意,如果将键<i>重新插入</ i>到map中,则不会影响插入顺序。 (map中put一个已经插入过的key值,containsKey将返回true)


 <p>This implementation spares its clients from the unspecified, generally chaotic ordering provided by @link HashMap (and @link Hashtable),  without incurring the increased cost associated with @link TreeMap.  It  can be used to produce a copy of a map that has the same order as the  original, regardless of the original map's implementation:
  <pre>
      void foo(Map m)
          Map copy = new LinkedHashMap(m);
          ...
     
  </pre>
  This technique is particularly useful if a module takes a map on input,  copies it, and later returns results whose order is determined by that of  the copy.  (Clients generally appreciate having things returned in the same
  order they were presented.)


 <p>此实现使客户端免受@link HashMap(以及@link Hashtable)的无序,也不会导致使用@link TreeMap相关的成本增加。无论原始地图的实现如何,它都可用于生成与原始map具有相同顺序的map副本:
<PRE>
void foo(Map m)
Map copy = new LinkedHashMap(m);
...

</ PRE>
这个是一个特别有用的技术,输入一个map,复制它,返回结果,它的顺序取决于原复制对象。 (客户一般都倾向于返回顺序跟插入顺序一致)


  <p>A special @link #LinkedHashMap(int,float,boolean) constructor is  provided to create a linked hash map whose order of iteration is the order  in which its entries were last accessed, from least-recently accessed to  most-recently (<i>access-order</i>).  This kind of map is well-suited to  building LRU caches.  Invoking the @code put, @code putIfAbsent,
  @code get, @code getOrDefault, @code compute, @code computeIfAbsent,  @code computeIfPresent, or @code merge methods results  in an access to the corresponding entry (assuming it exists after the  invocation completes). The @code replace methods only result in an access  of the entry if the value is replaced.  The @code putAll method generates one  entry access for each mapping in the specified map, in the order that  key-value mappings are provided by the specified map's entry set iterator.  <i>No other methods generate entry accesses.</i>  In particular, operations  on collection-views do <i>not</i> affect the order of iteration of the  backing map.


 <p>提供了一个特殊的@link LinkedHashMap(int,float,boolean)构造函数来创建LinkedHashMap,其迭代顺序是上次访问其条目的顺序,从最少访问到最远访问(<I>存取顺序</ i>的)。这种map非常适合构建LRU缓存。调用@code put,@ code putIfAbsent,@code get,@ code getOrDefault,@ code compute,@ code computeIfAbsent,@ code computeIfPresent或@code merge方法会导致访问相应的条目(假设它存在于调用完成)。如果替换了值,@code replace方法只会导致访问该替换条目。 @code putAll方法为指定映射中的每个映射生成一个条目访问,按照指定映射的条目集迭代器提供键 - 值映射的顺序。 <i>没有其他方法可以生成条目访问。</ i>特别是,对集合视图的操作<i>不</ i>会影响后备映射的迭代顺序。


<p>The @link #removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.


 <p>可以重写@link removeEldestEntry(Map.Entry)方法,以强制在将新映射添加到map时自动删除过时映射的策略。


  <p>This class provides all of the optional <tt>Map</tt> operations, and  permits null elements.  Like <tt>HashMap</tt>, it provides constant-time  performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and  <tt>remove</tt>), assuming the hash function disperses elements  properly among the buckets.  Performance is likely to be just slightly  below that of <tt>HashMap</tt>, due to the added expense of maintaining the  linked list, with one exception: Iteration over the collection-views  of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>  of the map, regardless of its capacity.  Iteration over a <tt>HashMap</tt>  is likely to be more expensive, requiring time proportional to its  <i>capacity</i>.
 

<p>此类提供所有可选的<tt> Map </ tt>操作,并允许null元素。与<tt> HashMap </ tt>一样,它为基本操作提供了恒定时间性能(<tt> add </ tt>,<tt>contains</ tt>和<tt> remove </ tt>),假设散列函数在桶之间正确地分散元素。由于维护链表的额外费用,性能可能略低于<tt> HashMap </ tt>的性能,但有一个例外:迭代<tt> LinkedHashMap的集合视图</ tt>需要与map的<i>size</ i>成比例的时间,无论其容量如何。对<tt> HashMap </ tt>的迭代可能更昂贵,需要时间与其<i>capacity</ i>成比例。


<p>A linked hash map has two parameters that affect its performance: <i>initial capacity</i> and <i>load factor</i>.  They are defined precisely  as for <tt>HashMap</tt>.  Note, however, that the penalty for choosing an  excessively high value for initial capacity is less severe for this class  than for <tt>HashMap</tt>, as iteration times for this class are unaffected  by capacity.


 <p>链接哈希映射有两个影响其性能的参数:<i>初始容量</ i>和<i>加载因子</ i>。它们的定义与<tt> HashMap </ tt>完全相同。但是请注意,对于此类,选择过高的初始容量值的代价要小于<tt> HashMap </ tt>,因为此类的迭代次数不受容量的影响。


<p><strong>Note that this implementation is not synchronized.</strong>  If multiple threads access a linked hash map concurrently, and at least  one of the threads modifies the map structurally, it <em>must</em> be  synchronized externally.  This is typically accomplished by  synchronizing on some object that naturally encapsulates the map.

 

<p> <strong>请注意,此实现未同步。</ strong>如果多个线程同时访问链接的哈希映射,并且至少有一个线程在结构上修改了映射,则<em>必须</ em>外部同步。这通常通过在自然封装map的某个对象上进行同步来实现。


  If no such object exists, the map should be "wrapped" using the  @link Collections#synchronizedMap Collections.synchronizedMap  method.  This is best done at creation time, to prevent accidental
  unsynchronized access to the map:<pre>    Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre>
 

如果不存在此类对象,则应使用@link CollectionssynchronizedMap Collections.synchronizedMap方法“包装”该映射。这最好在创建时完成,以防止意外
对地图的非同步访问:<pre> Map m = Collections.synchronizedMap(new LinkedHashMap(...)); </ pre>


A structural modification is any operation that adds or deletes one or more  mappings or, in the case of access-ordered linked hash maps, affects  iteration order.  In insertion-ordered linked hash maps, merely changing  the value associated with a key that is already contained in the map is not  a structural modification.  <strong>In access-ordered linked hash maps,  merely querying the map with <tt>get</tt> is a structural modification.  </strong>)


 结构修改是添加或删除一个或多个映射的任何操作,或者在访问顺序链接的哈希映射的情况下,影响迭代顺序。在插入有序链接散列映射中,仅更改与已包含在映射中的键相关联的值不是结构修改。 <strong>在访问顺序链接哈希映射中,仅使用<tt> get </ tt>查询映射是一种结构修改。 </强>)


<p>The iterators returned by the <tt>iterator</tt> method of the collections  returned by all of this class's collection view methods are  <em>fail-fast</em>: if the map is structurally modified at any time after  the iterator is created, in any way except through the iterator's own  <tt>remove</tt> method, the iterator will throw a @link  ConcurrentModificationException.  Thus, in the face of concurrent  modification, the iterator fails quickly and cleanly, rather than risking  arbitrary, non-deterministic behavior at an undetermined time in the future.


 <p>所有类的集合视图方法返回的集合的<tt> iterator </ tt>方法返回的迭代器是<em> fail-fast </ em>:如果map在任何时候都是结构修改的在创建迭代器之后,除了通过迭代器自己的<tt> remove </ tt>方法之外,迭代器将抛出@link ConcurrentModificationException。因此,在并发修改的情况下,迭代器快速而干净地失败,而不是在未来的未确定时间冒着任意的,非确定性行为的风险。


  <p>Note that the fail-fast behavior of an iterator cannot be guaranteed  as it is, generally speaking, impossible to make any hard guarantees in the  presence of unsynchronized concurrent modification.  Fail-fast iterators  throw <tt>ConcurrentModificationException</tt> on a best-effort basis.  Therefore, it would be wrong to write a program that depended on this  exception for its correctness:   <i>the fail-fast behavior of iterators  should be used only to detect bugs.</i>


 <p>请注意,迭代器的快速失败行为无法得到保证,因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬性保证。失败快速迭代器会尽最大努力抛出<tt> ConcurrentModificationException </ tt>。因此,编写依赖于此异常的程序以确保其正确性是错误的:<i>迭代器的故障快速行为应仅用于检测错误。</ i>


  <p>The spliterators returned by the spliterator method of the collections  returned by all of this class's collection view methods are  <em><a href="Spliterator.html#binding">late-binding</a></em>,  <em>fail-fast</em>, and additionally report @link Spliterator#ORDERED.
 

<p>由所有类的集合视图方法返回的集合的spliterator方法返回的分裂器是<em> <a href='Spliterator.htmlbinding'>late-binding</a> </ em>,<em >fail-fast</ em>,并另外报告@link SpliteratorORDERED。

以上是关于源码分析——What is LinkedHashMap的主要内容,如果未能解决你的问题,请参考以下文章

源码分析——What is LinkedHashMap

源码分析——What is LinkedHashMap

源码分析——What is LinkedList

源码分析——What is LinkedList

源码分析——What is ArrayList

源码分析——What is ArrayList