/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 判断列表的capacity容量是否足够,是否需要扩容 ensureCapacityInternal(size + 1); // Increments modCount!! // 将元素添加进列表的元素数组里面 elementData[size++] = e; return true; } /** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10;
/** * 列表元素集合数组 * 如果新建ArrayList对象时没有指定大小,那么会将EMPTY_ELEMENTDATA赋值给elementData, * 并在第一次添加元素时,将列表容量设置为DEFAULT_CAPACITY */ transient Object[] elementData;
/** *列表大小,elementData中存储的元素个数 */ private int size;
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); }
ensureExplicitCapacity(minCapacity); }
private void ensureExplicitCapacity(int minCapacity) { modCount++;
// overflow-conscious code if (minCapacity - elementData.length > ) grow(minCapacity); }
private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < ) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > ) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
ArrayIndexOutOfBoundsException
elementData[size] = e;size = size + 1;
import java.util.ArrayList;import java.util.List;
public class ArrayListSafeTest {
public static void main(String[] args) throws InterruptedException {
final List<Integer> list = new ArrayList<Integer>(); // 线程A将1-1000添加到列表 new Thread(new Runnable() {
public void run() { for (int i = 1; i < 1000; i++) { list.add(i);
try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
}
}).start(); // 线程B将1001-2000添加到列表 new Thread(new Runnable() {
public void run() { for (int i = 1001; i < 2000; i++) { list.add(i);
try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
}
}).start(); Thread.sleep(1000);
// 打印所有结果 for (int i = ; i < list.size(); i++) { System.out.println("第" + (i + 1) + "个元素为:" + list.get(i)); } }}

List<Object> list =Collections.synchronizedList(new ArrayList<Object>);
synchronized(list.get()) {list.get().add(model);}
List<Object> list1 = new CopyOnWriteArrayList<Object>();
ThreadLocal<List<Object>> threadList = new ThreadLocal<List<Object>>() { protected List<Object> initialValue() { return new ArrayList<Object>(); }};
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31537575/viewspace-3160585/ ,如需转载,请注明出处,否则将追究法律责任。