File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33众所周知 ` HashMap ` 是一个无序的 ` Map ` ,因为每次根据 ` key ` 的 ` hashcode ` 映射到 ` Entry ` 数组上,所以遍历出来的顺序并不是写入的顺序。
44
5- 因此 JDK 推出一个基于 HashMap 但具有顺序的 LinkedHashMap 来解决有排序需求的场景。
5+ 因此 JDK 推出一个基于 ` HashMap ` 但具有顺序的 ` LinkedHashMap ` 来解决有排序需求的场景。
66
77它的底层是继承于 ` HashMap ` 实现的,由一个双向链表所构成。
88
182182 }
183183```
184184
185- 主体的实现都是借助于 ` HashMap ` 来完成的,只是对其中的 ` recordAccess(),createEntry (), createEntry() ` 进行了重写。
185+ 主体的实现都是借助于 ` HashMap ` 来完成的,只是对其中的 ` recordAccess(), addEntry (), createEntry() ` 进行了重写。
186186
187187` LinkedHashMap ` 的实现:
188188
216216 table[bucketIndex] = e;
217217 e. addBefore(header);
218218 size++ ;
219- }
219+ }
220+
221+ // 写入到双向链表中
222+ private void addBefore(Entry<K ,V > existingEntry) {
223+ after = existingEntry;
224+ before = existingEntry. before;
225+ before. after = this ;
226+ after. before = this ;
227+ }
228+
229+ ```
230+
231+ ## get 方法
232+
233+ LinkedHashMap 的 ` get() ` 方法也重写了:
234+
235+ ``` java
236+ public V get(Object key) {
237+ Entry<K ,V > e = (Entry<K ,V > )getEntry(key);
238+ if (e == null )
239+ return null ;
240+
241+ // 多了一个判断是否是按照访问顺序排序,是则将当前的 Entry 移动到链表末尾
242+ e. recordAccess(this );
243+ return e. value;
244+ }
220245```
221246
222247
You can’t perform that action at this time.
0 commit comments