JDK原始碼走讀(4) 容器之LinkedList

2021-07-26 06:49:44 字數 2388 閱讀 3445

本章分析list系列中的linkedlist,真正意義上的鍊錶,底層採用鍊錶形式儲存資料元素。linkedlist是乙個雙向鍊錶,可以向前或向後兩個方向遍歷鍊錶。linkedlist也可以存放null元素。

一、 類實現/繼承體系結構

為了對整個list實現/繼承體系有個全貌,先將體系結構圖畫出來:

二、 關鍵資料成員

(1)節點類

(2)首尾節點

為了更便利的操作鍊錶,比如在鍊錶末尾新增刪除元素,linkedlist提供了首尾兩個節點引用:

transient nodefirst;

transient nodelast;

(3)鍊錶存放的元素個數

transient int size = 0;

三、 建構函式

linkedlist提供了兩種形式的建構函式:

publiclinkedlist ()

publiclinkedlist (collection<? extends e> c):利用另乙個集合初始化linkedlist,要求就是負責初始化集合中的元素型別是e或者是e的子類。

四、 增

(1)  void addfirst(e e):將值為e的元素加入到鍊錶頭部,會呼叫linkfirst:

private voidlinkfirst(e e) {

final nodef = first;

final nodenewnode = new node<>(null,e, f);

first = newnode;

if (f == null)

last = newnode;

else

f.prev = newnode;

size++;

modcount++;

(2)  void addlast(e e):將值為e的元素加入到鍊錶尾部,跟addfirst類似,只是將元素加到鍊錶尾部;

(3)  boolean add(e e):預設加到鍊錶的末尾,linklast(e);

(4)  boolean addall(collection<? extends e> c)與

booleanaddall(int index, collection<? extends e> c)都是將容器c中的元素新增到鍊錶中,不帶index的介面,預設加到鍊錶尾部,所以實現也是呼叫帶index的介面:

publicboolean addall(collection<? extends e> c) {

returnaddall(size, c);

(5)  boolean offer(e e):新增到鍊錶尾部,同offerlast

(6)  boolean offerfirst(e e):新增到鍊錶頭部

五、 刪

(1)  e removefirst():刪除鍊錶第乙個元素,首先判斷first是否合法,然後呼叫unlinkfirst:

private eunlinkfirst(nodef) {

// assert f == first && f !=null;

final e element = f.item;

final nodenext = f.next;

f.item = null;

f.next = null; // help gc

first = next;

if (next == null)

last = null;

else

next.prev = null;

size--;

modcount++;

return element;

(2)  e removelast():刪除最後乙個元素,與removefirst類似,呼叫unlinklast實現刪除最後乙個元素;

(3)  boolean remove(object o)

(4)  public e poll():返回並刪除第乙個元素;

(5)  public e remove():刪除第乙個元素;

(6)   

六、 改

(1)  e set(int index, e element):設定index位置的元素值

七、 查

(1)  e getfirst():獲取第乙個元素;

(2)  e getlast():獲取最後乙個元素;

(3)  boolean contains(object o):是否包含元素o,使用indexof函式判斷,不包含返回-1;

(4)  public e peek():返回第乙個元素,如果鍊錶為空,返回null;

(5)  public e element():返回第乙個元素,如果鍊錶為空,則丟擲異常nosuchelement;

(6)  public e poll()

八、 遍歷

類似於arraylist

原始碼解析 JDK原始碼之LinkedHashMap

linkedhashmap原始碼,基於 jdk1.6.43 他繼承了hashmap,並且實現了插入和訪問的有序功能 public class linkedhashmapextends hashmapimplements map 其也有乙個entry內部類,繼承了 hashmap 的entry 內部類...

JDK原始碼之Map

1.hashmap hashmap初始化的方式有四種。建立乙個entry陣列,預設初始長度為16,當大於0.75的時候,擴充套件為當前的2倍。有4中初始化map的方式。mapmap new hashmap mapmap2 new hashmap 17 mapmap3 new hashmap 15,2...

JDK原始碼之PriorityQueue原始碼剖析

優先佇列在程式開發中屢見不鮮,比如作業系統在進行程序排程時一種可行的演算法是使用優先佇列,當乙個新的程序被fork 出來後,首先將它放到佇列的最後,而作業系統內部的scheduler負責不斷地從這個優先佇列中取出優先順序較高的程序執行 爬蟲系統在執行時往往也需要從乙個優先順序佇列中迴圈取出高優先順序...