1、通过iterator遍历arraylist的时候要特别注意并发问题,通过modCount记录了arrayList的改变次数,通过此provide fail-fast iterators
* <p>The iterators returned by this class's <tt>iterator</tt> and
* <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
* structurally modified at any time after the iterator is created, in any way
* except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
* the iterator will throw a {@link ConcurrentModificationException}. 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.<p>
2、arraylist属性
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData; //非序列化
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size; //标注list元素数量
3、构造函数
(1)、在构造函数中有一段:
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);
}
查看了Arrays.copyOf,public static <T> T[] copyOf(T[] original, int newLength),注释中有这么一段说明 The resulting array is of exactly the same class as the original array.
4、方法
(1)、contains方法,内部调用了indexOf方法,而indexOf方法是对整个数组循环遍历
(2)、arrayList的writeObject:
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount; //保证在序列化前后没有对list进行修改
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
付:defaultWriteObject:将当前类的非静态和非瞬态字段写入此流
(3),readObject:
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}