LinkedList
implementationCollections.synchronizedList 方法。最好的做法是在创建时,防止其他非同步访问列表。
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's iterator
and listIterator
methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove
or add
methods, the iterator will throw aConcurrentModificationException
. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.。ConcurrentModificationException
on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugspublic ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }
public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; }
public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
public void ensureCapacity(int minCapacity) { // 判断是否一个 空数组,如果是返回 DEFAULT_CAPACITY ,主要就是告诉你,别犯贱在ArrayList声明还没使用的情况下就设置一个小于默认值的容量进来。 int minExpand = (elementData != EMPTY_ELEMENTDATA) // any size if real element table ? 0 // larger than default for empty table. It's already supposed to be // at default size. : DEFAULT_CAPACITY; if (minCapacity > minExpand) { ensureExplicitCapacity(minCapacity); } }
public void trimToSize() { modCount++; if (size < elementData.length) { elementData = Arrays.copyOf(elementData, size); } }
7.Fail-Fast机制: