public class ArrayList<E> extends AbstractList<E> implements List<E>
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
ublic abstract class AbstractCollection<E> implements Collection<E>
public interface Collection<E> extends Iterable<E>
A extends B implements C(C可以是B实现的接口的子接口)
// ArrayList扩容机制 1.5倍扩容
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 位运算 n向右移动1位=n/2
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
非线程安全。想要用线程安全的list使用以下两种办法
List list = Collections.synchronizedList(list1);
// 当用户通过迭代器遍历返回列表时,必须手动同步 增强for循环底层也是iterator
List list = Collections.synchronizedList(new ArrayList());
...
synchronized (list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
CopyOnWriteArrayList list2 = new CopyOnWriteArrayList();
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements;
if (c.getClass() == CopyOnWriteArrayList.class)
elements = ((CopyOnWriteArrayList<?>)c).getArray();
else {
elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elements.getClass() != Object[].class)
// 原数组复制Arrays.copyOf
elements = Arrays.copyOf(elements, elements.length, Object[].class);
}
setArray(elements);
}
优点
支持高效率并发且是线程安全的。
对其进行的修改操作都是在底层的一个复制数组(快照)上进行的,也就是使用了写时复制策略。
场景
合适读多写少的场景。
此做法主要的优点是如果调用者没有修改资源,就不会有副本被创建,因此多个调用者只是读取操作时可以共享同一份资源。
缺点:
- 由于写操作的时候,需要拷贝数组,会消耗内存,如果原数组的内容比较多的情况下,可能导致young gc或者full gc。
- 不能用于实时读的场景,像拷贝数组、新增元素都需要时间,所以调用一个set操作后,读取到数据可能还是旧的,虽然CopyOnWriteArrayList 能做到最终一致性,但是还是没法满足实时性要求。