ArrayList是List接口的可扩容数组实现,可以存放任何元素,包括null。ArrayList在功能上基本等同于Vector,区别是ArrayList是非同步的、非线程安全的,而Vector是同步的、线程安全的。如果需要用到线程安全的list,则可以通过
List list = Collections.synchronizedList(new ArrayList(...));
ArrayList的默认初始化容量是10
private static final int DEFAULT_CAPACITY = 10;
/** * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
当经过不断操作之后,数组的容量大于实际存放的元素个数,可以通过调用以下方法缩小容量,减少空间占用。
/** * Trims the capacity of this <tt>ArrayList</tt> instance to be the * list's current size. An application can use this operation to minimize * the storage of an <tt>ArrayList</tt> instance. */ public void trimToSize()
/** * Removes all of the elements from this list. The list will * be empty after this call returns. */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }