1. ArrayList 在底层维护一个 Object[] ,如果你使用了泛型,其实是维护一个泛型指定类型的数组对象
/**
* 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 E[] elementData;
ArrayList维护的数组的长度表示一个“容量”,用户一般不主动维护“容量”这个值,我们通常要使用的是数组的长度,也就是你add了多少个对象。
2. 用户通过ArrayList对象的size()方法得到ArrayList实例中对象的数目
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list.
*/
public int size() {
return size;
}
当我们进行add remove等操作的时候,ArrayList对象会自动维护size值
3. ArrayList 的构造方法
(1)指定“容量”的构造方法
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list.
* @exception IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = (E[])new Object[initialCapacity];
}
如果在实例化ArrayList类的时候,指定了“容量”,那么ArrayList会生成一个指定容量大小的数组
(2)默认构造方法
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
(3) 构造一个与指定集合内容相同的ArrayList
/**
* @param c the collection whose elements are to be placed into this list.
* @throws NullPointerException if the specified collection is null.
*/
public ArrayList(Collection<? extends E> c) {
size = c.size();
// Allow 10% room for growth
int capacity = (int) Math.min((size*110L)/100, Integer.MAX_VALUE);
elementData = (E[]) c.toArray(new Object[capacity]);
}
使用这个构造方法生成的对象与参数Collection<? extends E> c 的hashCode值是相同的,但是二者互不影响。
此时,ArrayList实例的“容量”是参数Collection<? extends E> c 的size(一定要注意是size,不是c的“容量”)的110%+1