前言
LinkedList相對ArrayList來說可以使用頻率可能相對較低,但是對于不同需求到情況下我們需要能夠選擇合適的集合寂屏,本文將結(jié)合JDK1.8源碼從線程安全尚胞、數(shù)據(jù)結(jié)構(gòu)、初始化宇葱、增刪改查筷黔、特性總結(jié)等幾個部分去分析LinkedList
線程安全
ArrayList是非線程安全的往史,不支持并發(fā)。我們可以從它的數(shù)據(jù)迭代器ArrayList$Itr中可以得知佛舱,當(dāng)產(chǎn)生線程安全問題時會拋出拋出ConcurrentModificationException異常椎例。內(nèi)部是通過一個modCount變量記錄集合的變化,在擴(kuò)容與刪除及清空等操作都會將modCount自增请祖,以此來標(biāo)記集合的改變订歪。
如何實(shí)現(xiàn)線程安全
1.通過Colletions.synchronizedCollection獲取線程安全的集合對象
2.使用并發(fā)庫下的ConcurrentLinkedQueue或者ConcurrentLinkedDeque(讀寫分離)
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
...
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
數(shù)據(jù)結(jié)構(gòu)
LinkedList采用雙向鏈表對數(shù)據(jù)進(jìn)行管理,通過指針形式的鏈接實(shí)現(xiàn)多個對象多有序排列肆捕,因此相對于ArrayList的數(shù)組形式來說刷晋,LinkedList的實(shí)現(xiàn)方式使得增刪更加高效。而改查時由于需要遍歷鏈表慎陵,所以相對低效掏秩。
初始化
提供了兩個重載構(gòu)造方法,除了默認(rèn)的無參構(gòu)造器外還可以指定初始集合內(nèi)容荆姆。為什么比ArrayList少了個指定容量的構(gòu)造方法呢?實(shí)際上映凳,鏈表構(gòu)成的LinkedList沒有容量的概念胆筒,它做的只是將某些對象封裝為node,而node之間通過指針指向來形成有序的集合。在指定初始集合時仆救,實(shí)際就是調(diào)用addAll方法將所有元素進(jìn)行添加操作抒和,這個后續(xù)會講到。
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
增操作
增操作首先進(jìn)行一些基本條件判斷彤蔽,指定的index是否越界摧莽。主要的實(shí)現(xiàn)即通過對節(jié)點(diǎn)元素對pre和next指針的指向來鏈接插入元素。
以下是add方法的分析:
void linkLast(E e) {
final Node<E> l = last; // 緩存此時的last
final Node<E> newNode = new Node<>(l, e, null); // 為元素生成node對象
last = newNode; // 指定新last
if (l == null) // 如果原本last為null那么表示之前沒有任何元素
first = newNode; // 將first也指定為該元素
else
l.next = newNode; // 否則將原本的last.next指定為該元素
size++; // 數(shù)量遞增
modCount++; // modCount遞增(用于線程安全檢測)
}
以下是addAll方法的分析:
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index); // 越界檢查
Object[] a = c.toArray(); // 將Collection轉(zhuǎn)為數(shù)據(jù)顿痪,便于循環(huán)遍歷
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ; // pred記錄目標(biāo)位置的前一個元素镊辕,succ用于記錄目標(biāo)位置
if (index == size) { // 如果目標(biāo)位置為末尾
succ = null; // 目標(biāo)位置為null
pred = last; // 目標(biāo)位置前一個即為last
} else { // 否則目標(biāo)位置為某個元素
succ = node(index); // 獲取目標(biāo)元素
pred = succ.prev; // 記錄目標(biāo)元素pred元素
}
for (Object o : a) { // 循環(huán)數(shù)組
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null); // 為其生成node對象
if (pred == null) // 如果pred為null表示此前沒有元素
first = newNode; // 指定為first
else
pred.next = newNode; // 指定為目標(biāo)元素的next
pred = newNode; // 將pred賦值為該節(jié)點(diǎn),為下個元素拼接做準(zhǔn)備
}
if (succ == null) { // 如果succ為null表示在這之前沒有任何元素蚁袭,那么last指定為最后的pred即可
last = pred;
} else { // 否則將拼接后的末尾next指定為之前取得的目標(biāo)位置succ
pred.next = succ;
succ.prev = pred; // 而succ的prev指定為pred
}
size += numNew; // 數(shù)量更新
modCount++; // modCount遞增(用于線程安全檢測)
return true; // 返回true表示添加成功
}
刪操作
刪除操作通過將目標(biāo)位置的前后拼接到一起征懈,從而使目標(biāo)位置的元素脫離整個鏈表結(jié)構(gòu),以此達(dá)到刪除操作的目的揩悄。
public boolean remove(Object o) {
// 區(qū)分元素是否為null卖哎,證明LinkedList支持添加null對象
if (o == null) {
// 通過從first到開始不斷next的方法循環(huán)整個鏈表
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) { // 如果節(jié)點(diǎn)的值為null,則是我們要移除的目標(biāo)
unlink(x); // 將目標(biāo)從鏈表中unlink掉
return true; // 返回true 表示移除成功
}
}
} else { // 不為null元素的情況下
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false; // 沒有找到指定元素删性,返回false
}
// unlink, 將指定元素從鏈表中移除
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item; // 記錄元素的value
final Node<E> next = x.next; // 記錄指定元素next
final Node<E> prev = x.prev; // 記錄指定元素prev
// 如果指定元素prev為null亏娜,表示目標(biāo)元素為first
// 直接將first指定為目標(biāo)元素的next即可
if (prev == null) {
first = next;
} else {
// 如果指定元素位于中間或者末尾
// 則指定其prev.next為目標(biāo)元素的next,即將目標(biāo)元素分隔開
prev.next = next;
x.prev = null; // 此處指定目標(biāo)元素的prev為null是為了利于gc蹬挺,避免泄漏
}
// 如果目標(biāo)元素next為null表示它處于末尾维贺,需要更新last
if (next == null) {
last = prev;
} else {
// 否則目標(biāo)元素處于中間,需要更新其next的prev指向
next.prev = prev;
x.next = null; // 此處指定目標(biāo)元素的prev為null是為了利于gc汗侵,避免泄漏
}
x.item = null; // 元素value置空
size--; // 更新數(shù)量
modCount++; // modCount遞增(用于線程安全)
return element; // 返回被刪除的對象
}
改操作
很簡單幸缕,越界檢查 - > 得到目標(biāo) - > 修改 - > 返回原值
public E set(int index, E element) {
checkElementIndex(index); // 越界檢查
Node<E> x = node(index); // 得到目標(biāo)對象節(jié)點(diǎn)
E oldVal = x.item; // 記錄old value
x.item = element; // 修改為new value
return oldVal; // 返回old value
}
// 用于得到指定位置的節(jié)點(diǎn)
Node<E> node(int index) {
// assert isElementIndex(index);
// 此處進(jìn)行簡單的二分判斷,決定鏈表遍歷的方向晰韵,提升效率
if (index < (size >> 1)) { // 小于數(shù)量一半
Node<E> x = first; // 從頭部開始遍歷
for (int i = 0; i < index; i++) // 得到index節(jié)點(diǎn)
x = x.next;
return x;
} else { // 大于數(shù)量一半
Node<E> x = last; // 從尾部開始遍歷
for (int i = size - 1; i > index; i--) // 得到index節(jié)點(diǎn)
x = x.prev;
return x;
}
}
查操作
很簡單发乔,越界檢查 - > 得到目標(biāo)節(jié)點(diǎn)返回對象
public E get(int index) {
checkElementIndex(index); // 越界檢查
return node(index).item; // 同上分析
}
特性總結(jié)
1.數(shù)據(jù)結(jié)構(gòu)為雙向鏈表,增刪快雪猪、改查慢
2.由于使用鏈表的結(jié)構(gòu)栏尚,所以沒有擴(kuò)容操作
3.在查找元素時會進(jìn)行區(qū)間折半,提升查找效率