實際上,LinkedList#removeFirst
更有效率,因爲它是通過雙向鏈表進行操作的,並且刪除第一個元素基本上只是將其從列表頭開始鏈接,並將下一個元素更新爲第一個元素:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
另一方:
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = 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;
}
ArrayList#remove
上方這需要通過在子陣列複製shiftting所有subsequents元件的一個位置向左側的內部陣列操作手,LinkedList#get
操作需要遍歷整個列表的一半來檢索指定索引處的元素 - 在最壞的情況下。 ArrayList#get
將直接訪問指定索引處的元素,因爲它在數組上運行。
在這裏,我的大拇指效率的規則是:
- 使用
LinkedList
如果你做了很多的add
/remove
在比較 檢索操作(例如:get
);
- 如果您與
add
/remove
比較檢索操作做了很多 ,請使用ArrayList
。
一)定義的性能。有許多變量需要衡量,例如時間,效率,內存使用情況等。b)編寫一些測試代碼,使用秒錶(而不是物理)以及這種性質的事物來進行基準測試並找出結果。 –
「做這件事最有效的方法是什麼?」取決於你的情況。請參閱http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist – Shar1er80