1.ArrayList是實現了基於動態數組的數據結構,LinkedList基於鏈表的數據結構。
2.對於隨機訪問get和set,ArrayList覺得優於LinkedList,LinkedList要移動指針。
3.對於新增和刪除操作add和remove,LinkedList比較佔優勢,ArrayList要移動數據。
ArrayList的方法
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
ArrayList 初始化存儲空間的大小是10 然後以後以1.5+1的級數增長,在這個過程中先new 原來空間的1.5倍+1的新空間,然後把原來的數據拷貝到新的空間,所以說ArrayList 的添加數據的性能低於LinkedList
接下來繼續看LinkedList的add方法
public boolean add(E e) {
addBefore(e, header);
return true;
}
private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
entry.previous.next = newEntry;
entry.next.previous = newEntry; //粗體部分 進行 修正 2010-11-29
size++;
modCount++;
return newEntry;
}
是雙向鏈表的添加操作,這是數據結構裏面的必修煉的功力之一,在添加的時候只要修改一下指針就ok了,沒有ArrayList 的增長空間拷貝數據的步驟,所以總體上看來在add的時候,LinkedList比ArrayList 快
下面來看看ArrayList 的get方法
public E get(int index) {
RangeCheck(index);
return (E) elementData[index];
}
RangeCheck 檢測訪問是否越界,然後根據索引下標直接返回值,果然快。
再來看看LinkedList的get方法
public E get(int index) {
return entry(index).element;
}
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
一個一個去找是比較的慢,不過還是優化了,如果要找的數小於等於size的一半就從頭往後找,要是大於size的一半就從後往前找,LinkedList的get和ArrayList 比起來確實慢了很多。