- ArrayList 本质实现是数组,对于数组而言频繁的访问效率比频繁的插入/删除效率更高,插入和删除会导致其他元素移动,当add时超出自己容量时会进行1.5倍扩容
- ArrayList的clone最终是靠System.arraycopy实现的,System.arraycopy是浅拷贝,且不是线程安全的
//ArrayList的clone方法,最终调用的System.arraycopy
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
3.ArrayList不是线程同步的,多线程 场景下要使用Collections.synchronizedList返回线程安全的集合,或者使 用CopyOnWriteArrayList