首先,回顧一下ArrayList和數組有什麼區別?
初始化大小:ArrayList可以不指定大小,數組必須指定大小
存儲數據類型:ArrayList只能存儲引用類型,數組可以存儲引用類型和基本類型
ArrayList比數組靈活(提供豐富的方法)
LinkedList:
特點:
- 數據按照插入有序
- 可以存儲null值
- 可以重複存儲數據
- 底層數據結構爲鏈表
LinkedList源碼解讀
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
extends AbstractSequentialList< E > : 對List接口的實現
implements Deque< E > : 具有隊列的特徵(先進先出 )
提供了特殊的方法,從頭、從尾進行添加、刪除、獲取
屬性
transient int size = 0; 集合中元素個數
transient Node first; 頭結點
transient Node last; 尾結點
private static class Node<E> {
E item; 存儲元素
Node<E> next; 後繼節點
Node<E> prev; 前驅節點
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
底層數據結構:雙向鏈表
構造函數
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
add()添加元素
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
LinkedList提供頭插,尾插方式插入節點、默認採用的是尾插
get() 獲取元素
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
remove 刪除元素
public boolean remove(Object o) {
//判斷元素是否爲null進行不同的判等處理
//刪除元素從前往後刪除,重複性元素直接刪除第一個節點
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
//前驅prev分兩種情況:一種是first節點,一種非first節點
if (prev == null) {
//當前節點是first節點
first = next;
} else {
prev.next = next;
x.prev = null;
}
//後繼next分兩種情況:一種是last節點,一種是非last節點
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
//將元素置爲null
x.item = null;
size--;
modCount++;
return element;
}
最後,總結ArrayList、LinkedList的異同點,各自優勢(應用場景)
相同點:
1、繼承關係:List接口下的實現類,具有list提供的所有方法
2、有序性:數據都是按照插入有序
3、重複性:集合中元素是可以重複的
4、null值:都可以存儲 null值
5、安全性:都是非線程安全的集合
不同點:
數據結構:ArrayList底層是數組、LinkedList底層是鏈表(雙向鏈表)
特有方法:LinkedList具有特有的方法,列如:addFirst、addLast…(實現Deque接口)
效率:ArrayList查詢效率高(O(1))、LinkedList添加、刪除效率高(O(1))
ArrayList添加元素趨近於O(1)(在不擴容情況下就是O(1))
應用場景不同:ArrayList在查詢較高的業務場景優先考慮,
LinkedList在修改、添加等操作較多的場景下優先考慮