ArrayList
實現了可變大小的數組,隨機訪問和遍歷元素時,提供更好的性能,插入刪除效率低。
構造方法
transient Object[] elementData;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
添加方法
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
查找方法
public E get(int index) {
rangeCheck(index);
return (E) elementData[index];
}
LinkedList
主要用於創建鏈表數據結構,查找效率低。
構造方法
public LinkedList() {}
添加方法
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
查找方法
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
Vector
Vector 是矢量隊列,它是 JDK1.0 版本添加的類。繼承於 AbstractList,實現了 List, RandomAccess, Cloneable 這些接口。
構造方法
public Vector() {
this(10);
}
添加方法
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
查找方法
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return (E) elementData[index];
}
CopyOnWriteArrayList
添加方法
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
線程安全 List
1、Vector 使用了 synchronized 關鍵字;
2、Collections.synchronizedList(list);
3、CopyOnWriteArrayList 併發類。