Skip to content

Commit e0a49ad

Browse files
committed
💬 update LinkedHashMap
1 parent eba0492 commit e0a49ad

1 file changed

Lines changed: 28 additions & 3 deletions

File tree

MD/collection/LinkedHashMap.md

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
众所周知 `HashMap` 是一个无序的 `Map`,因为每次根据 `key``hashcode` 映射到 `Entry` 数组上,所以遍历出来的顺序并不是写入的顺序。
44

5-
因此 JDK 推出一个基于 HashMap 但具有顺序的 LinkedHashMap 来解决有排序需求的场景。
5+
因此 JDK 推出一个基于 `HashMap` 但具有顺序的 `LinkedHashMap` 来解决有排序需求的场景。
66

77
它的底层是继承于 `HashMap` 实现的,由一个双向链表所构成。
88

@@ -182,7 +182,7 @@
182182
}
183183
```
184184

185-
主体的实现都是借助于 `HashMap` 来完成的,只是对其中的 `recordAccess(),createEntry(), createEntry()` 进行了重写。
185+
主体的实现都是借助于 `HashMap` 来完成的,只是对其中的 `recordAccess(), addEntry(), createEntry()` 进行了重写。
186186

187187
`LinkedHashMap` 的实现:
188188

@@ -216,7 +216,32 @@
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

0 commit comments

Comments
 (0)