他們都實現了 List 接口 都不是線程同步的.
ArrayList:無參構造方法
public ArrayList() {
this(10); //初始大小爲10
}
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
LinkedList 無參構造方法
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;
/**
* Constructs an empty list.
*/
public LinkedList() {
header.next = header.previous = header;
}
添加上的區別
ArrayList. add方法
public boolean add(E e) {
ensureCapacity(size + 1); // 確保數組有足夠的空間
elementData[size++] = e; //將對象添加到末尾.
return true;
}
在看下ensureCapacity 方法
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) { //如果數組容量不夠 則進行擴容
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1; //擴容到原來空間的1.5倍
if (newCapacity < minCapacity) //如果新空間小於最小的空間容量
newCapacity = minCapacity; //則使用最小空間容量
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity); //進行擴容的數組複製
}
}
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);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
LinkedList add 將對象添加到herart之前
LinkedList使用了鏈表結構.因此不需要維護空間的大小. 但是如果頻繁的調用會對系統性能上產生一定影響
和ArrayList相比 在add操作的時候 不如add的效率高.
但是在指定插入位置時候 效率LinkedList明顯會高於ArrayList
刪除任意對象 LinkedList也明顯高於ArrayList
在使用 forecah迭代操作時候 兩者速度相同
使用傳統 for循環 則ArrayList佔據優勢
對於數組實現ArrayList來說 隨機訪問(傳統for循環)是很快的. 但是LinkedList是基於鏈表實現的 使用隨機訪問效果會很差.