原始碼分析 LinkedHashMap

2021-10-20 18:38:55 字數 2515 閱讀 5487

通過上圖可以看出linkedhashmap直接繼承了hashmap介面,實現了map介面,間接實現了cloneableserializable介面

linkedhashmap擁有四個構造方法,由於直接繼承了hashmap,具體實現由此父類決定

在這幾個構造方法之前存在乙個重要的屬性accessorder,其決定了在迭代linkedhashmap時是以訪問順序還是以插入順序進行

/**

* the iteration ordering method for this linked hash map: true

* for access-order, false for insertion-order.

** @serial

*/final

boolean accessorder;

hashmapnode是用來儲存資料的,在linkedhashmap中對此結構進行了拓展,新增了before和after,以雙向鍊錶的形式儲存資料

static

class

entry

extends

hashmap.node

}

linkedhashmap()
// 呼叫了hashmap的無參構造方法,並設定為以插入順序進行迭代

public

linkedhashmap()

linkedhashmap(int initialcapacity)
// 設定map的的初始值,並由hashmap具體實現

public

linkedhashmap

(int initialcapacity)

linkedhashmap(int initialcapacity, float loadfactor)
// 設定map的初始值和載入因子

public

linkedhashmap

(int initialcapacity,

float loadfactor)

linkedhashmap(map extends k, ? extends v> m)
// 合併兩個map,呼叫父類的putmapentries()方法進行實現

public

linkedhashmap

(map<

?extendsk,

?extends

v> m)

在對linkedhashmap執行put()方法時,實際上是呼叫hashmap的put()方法,由於在上篇文章中已經說過這部分**,這裡只對關鍵**進行解釋

final v putval

(int hash, k key, v value,

boolean onlyifabsent,

boolean evict)

++modcount;if(

++size > threshold)

resize()

;afternodeinsertion

(evict)

;return null;

}

呼叫newnode()

node

newnode

(int hash, k key, v value, node

e)private

void

linknodelast

(linkedhashmap.entry

p)}

至此,向map中新增新元素的工作已經完成。在這個過程中,資料儲存在node陣列中,entry儲存了插入順序。

獲取資料主要由hashmap實現,這部分內容已經在上篇文章中講過,不做贅述

public v get

(object key)

通過linkedhashmap原始碼分析發現,該資料型別是通過內部的entry記錄資料的插入順序並組成雙向鍊錶。底層儲存資料的依舊是陣列、單向鍊錶和紅黑樹。也發現了與hashmap存在的異同。

相同點:

不同點:

閱讀原文

Java原始碼集合類LinkedHashMap學習1

linkedhashmap類簡介 jdk 1.7.0 67 linkedhashmap類繼承了hashmap類,也就是linkedhashmap類的功能幾乎和hashmap一樣。而linkedhashmap類就是擴充套件了乙個雙向鍊錶,使得可以按照 鍵 值 對插入的順序遍歷,這個是在hashmap類...

spring原始碼分析 spring原始碼分析

1.spring 執行原理 spring 啟動時讀取應用程式提供的 bean 配置資訊,並在 spring 容器中生成乙份相應的 bean 配置登錄檔,然後根據這張登錄檔例項化 bean,裝配好 bean 之間的依賴關係,為上 層應用提供準備就緒的執行環境。二 spring 原始碼分析 1.1spr...

思科VPP原始碼分析(dpo機制原始碼分析)

vpp的dpo機制跟路由緊密結合在一起。路由表查詢 ip4 lookup 的最後結果是乙個load balance t結構。該結構可以看做是乙個hash表,裡面包含了很多dpo,指向為下一步處理動作。每個dpo都是新增路由時的乙個path的結果。dpo標準型別有 dpo drop,dpo ip nu...