java數據結構之List(列表)

List列表允許存儲相同元素,插入元素和按照下標獲取元素方便,具體實現有ArrayList,LinkedList和Vector,

ArrayList底層基於數組實現的,按順序存儲元素以及快速按照元素下標進行獲取元素,不可同步的;

而Vector底層也是數組,可進行同步操作,在多線程環境下可以使用;

LinkedList鏈表的具體機制如下圖:可以在具體下標位置刪除和添加元素,在許多需要根據具體下標添加和刪除元素的應用場景下比ArrayList有更好的性能。

LinkedList

ArrayList和Vector的部分源碼分析:

//ArrayList的add()方法

public boolean add(E e) {

ensureCapacityInternal(size + 1); // Increments modCount!!

//在數組結尾下標添加元素

elementData[size++] = e;

return true;

}

//ArrayList的remove()方法

public E remove(int index) {

rangeCheck(index);

modCount++;

E oldValue = elementData(index);

//獲取移動的元素的個數

int numMoved = size - index - 1;

if (numMoved > 0)

//將移除元素的下標位置後的數組元素都往前移一位來填補空位,調用System.arraycopy方法調用虛擬機自帶的方法進行操作效率更高

System.arraycopy(elementData, index+1, elementData, index,

numMoved);

elementData[--size] = null; // clear to let GC do its work

return oldValue;

}

//Vector添加了synchronized 進行同步

public synchronized void addElement(E obj) {

modCount++;

ensureCapacityHelper(elementCount + 1);

elementData[elementCount++] = obj;

}

綜上:Array List在不需要同步操作及不需要頻繁刪除任意下標的元素時推薦使用,Vector是在同步場景下使用,LinkedList是在需要頻繁刪除和添加任意下標的元素時使用


分享到:


相關文章: