ArrayList(jdk1.6)
/**
* 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;
内部用Object[]数组存储数据
/**
* 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 = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
无参构造函数,默认创建容量为10的数组
含参构造函数,如容量为负数,则抛出异常
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
添加元素之前会先判断添加此元素时容量会不会不够,如不够则需要进行扩容
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
扩容方式后的新容量为(oldCapacity * 3)/2 + 1,如计算之后的新容量还是小于minCapacity(有可能添加的是一个集合),那么新容量就等于minCapacity。
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
在指定位置添加元素,扩容方式和之前一样,但会想判断边界index > size || index < 0则抛出异常(index=size或index=0代表插入尾和头),接下来会把从index开始往后的元素拷贝到从index+1往后的位置 ,再把新增的元素加到index处的位置。
插播一下Arrays.copyOf和System.arraycopy的区别,Arrays.copyOf内部实现其实就是调用System.arraycopy,只不过加了一层保护即取新长度和源数组长度的最小值,防止数据溢出。
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]>