ArrayList

实现和继承的类和接口

public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable

AbstractList继承AbstractCollection

/**
* 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;

elementData是底层存储的数组,使用了瞬时关键字,序列化的时候是真个数组对象序列化,而是将元素一个一个序列化,具体可看writeobject方法,而size是list中实际包含的元素的个数,

fast-fail的域

modCount继承自AbstractList,任何对list的修改调用modCount都递增,在迭代器中每次都会检查这个值是否与期望的一致,如果不一致就会抛出并发修改异常,所以不能直接在迭代中直接调用lisst的修改方法,迭代器中的改变list的方法会同时改变期望值,所以可以在迭代中调用。但是多线程的修改,两种方式都是不行的

扩容

/**
  * Increases the capacity of this ArrayList instance, if
  * necessary, to ensure that it can hold at least the number of elements
  * specified by the minimum capacity argument.
  *
  * @param   minCapacity   the desired minimum capacity
  */
public void ensureCapacity(int minCapacity) {
     if (minCapacity > 0)
         ensureCapacityInternal(minCapacity);
}

private void ensureCapacityInternal(int minCapacity) {
     modCount++;
     // overflow-conscious code
     if (minCapacity - elementData.length > 0)
         grow(minCapacity);
}

/**
  * The maximum size of array to allocate.
  * Some VMs reserve some header words in an array.
  * Attempts to allocate larger arrays may result in
  * OutOfMemoryError: Requested array size exceeds VM limit
  */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/**
  * Increases the capacity to ensure that it can hold at least the
  * number of elements specified by the minimum capacity argument.
  *
  * @param minCapacity the desired minimum capacity
  */
private void grow(int minCapacity) {
     // overflow-conscious code
     int oldCapacity = elementData.length;
     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);
}

private static int hugeCapacity(int minCapacity) {
     if (minCapacity < 0) // overflow
         throw new OutOfMemoryError();
     return (minCapacity > MAX_ARRAY_SIZE) ?
         Integer.MAX_VALUE :
         MAX_ARRAY_SIZE;
}

当size到达length时,一般是增大到3/2, 1.7增加了上限,大量使用Arrays.copyOf, 对于大数据量,最好可以先指定list大小创建,避免垃圾回收影响

remove(Object o)时,先搜索到index,然后调fastremove(index),省掉remove(index)中的检查index是否存在的部分并且不返回删除的对象的引用

remove方法参数用Object,因为调用了equals方法,containAll方法用Collection, addAll方法用Collection,add方法用E,注意这些泛型接口的设计

用sublist来调用range相关的方法,底层还是用来的list

ListIterator可以往回迭代

其他可以看看http://www.cnblogs.com/hzmark/archive/2012/12/19/ArrayList.html

你可能感兴趣的:(ArrayList)