在分析之前,我們線看一下具體的ArrayList 和 LinkedList 源碼分析
其實看完源碼后,我們多多少少能得出如下的結論
線性存儲
1. 隨機訪問優勢
public E get(int index) {
//檢查下標是否符合
rangeCheck(index);
//直接通過下標訪問,還有更快的么
return elementData(index);
}
2, 插入性能堪憂困難
刪除也會哦
//添加數據操作
public boolean add(E e) {
//先執行擴容
ensureCapacityInternal(size + 1); // Increments modCount!!
//添加數據
elementData[size++] = e;
return true;
}
//確認新的容量是否符合, 返回符合的容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
//使用指定容量擴容
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//擴容操作
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
//可以在這里看到,容量一旦不夠,就需要進行擴容,關鍵這個擴容是需要,復制完整的原始數據
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
鏈式存儲
1.訪問元素困難
//暴力遍歷查找,所以在大數據查找的時候簡直是災難
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;
}
}
2. 毫無壓力的插入
沒有擴容之后,操作看起來變得復雜,其實沒了拷貝之后,性能飛起
public boolean addAll(int index, Collection<? extends E> c) {
//檢查下標參數
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
//重點在這里,創建鏈結構
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
//記錄修改次數
modCount++;
return true;
}
總結
上面這些實際上是都是在極度條件的下判斷出來的, 只有在幾百條數據的時候,并且沒有刪除數據,適合日志這種類型的,我個人還是建議使用 ArrrayList, 為什么 ?
- 真實存儲的是引用(4字節),創建數據存儲空間,和ArrayList,LinkedList 沒關系
- 在創建的時候,盡量給予相當的容量,這樣ArrayList的性能能達到最佳的水平
- 這兩種數據結構都不支持,并非修改, 支持并發訪問
- 頻繁的在插入數據,例如,排序, 刪除, 還是自覺使用鏈式存儲吧