JDK版本為1.8.0_271,LinkedHashMap繼承了HashMap,LinkedHashMap在HashMap的基礎(chǔ)上維護(hù)了一個(gè)雙向鏈表,實(shí)現(xiàn)了可以根據(jù)插入順序/訪問順序(accessOrder=false/true)訪問Map集合。
關(guān)于HashMap的原理可以參考HashMap部分底層源碼解析
部分屬性:
/**
* 雙向鏈表頭節(jié)點(diǎn)
*/
transient LinkedHashMap.Entry<K,V> head;
/**
* 雙向鏈表尾節(jié)點(diǎn)
*/
transient LinkedHashMap.Entry<K,V> tail;
/**
* 默認(rèn)為accessOrder=false,表示按照插入順序迭代
* accessOrder=true,表示按照訪問順序迭代
*/
final boolean accessOrder;
內(nèi)部定義的Entry如下:
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after; // Node節(jié)點(diǎn)的前后指針
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
LinkedHashMap重寫了HashMap中的newNode()方法:文章來源:http://www.zghlxwxcb.cn/news/detail-849562.html
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e);
// 新增的鍵值對p也要尾插法掛到雙向鏈表
linkNodeLast(p);
return p;
}
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
linkNodeLast(p); // 新增的鍵值對p也要尾插法掛到雙向鏈表
return p;
}
// 鍵值對p要尾插法掛到雙向鏈表
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
// 尾插法掛載節(jié)點(diǎn)到雙向鏈表
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
8.4.2 圖示
文章來源地址http://www.zghlxwxcb.cn/news/detail-849562.html
到了這里,關(guān)于LinkedHashMap部分底層源碼解析的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!