Summary:
- public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
- ArrayList里面维护了一个Object[];size域指明当前数据存储到了何处;如果Object数组长度不够则重新分配一次长度;
- ArrayList、StringBuidler等虽然可以自动扩容,但是一旦容量扩大了就不再缩减!!!运行足够长时间ArrayList的object数组长度很可能就等于Integer.MAX_VALUE,这是很占内存的;需要手动的调用trimToSize()方法进行减容;
- 这里有很好的习惯就是如果我们要删除object[index]所引用的对象,需要object[index]=null,这样垃圾回收器才能回收对应的对象;object[]数组占用内存的大小=引用大小*object.length;
Fields:
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
transient Object[] elementData; //transient关键字表明该字段不会被序列化;这个字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化。
private int size;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
注意:modCount;该变量定义在AbstractList中;
Constructor:
//默认构造一个空的Object数组
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
//构造一个指定大小的Object数组
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
一般操作:
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
搜索indexOf():
//从第一个开始找;最差O(size)
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
rangeCheck();
//在后面的删除、插入、添加的方法中使用
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
get()
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
set()
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
add()
//先做扩容性检测
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
//先做扩容性检测
//index 后面的数据全部往后移动一位
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
//先做扩容性检测
//数据添加到当前Object数组中的size位置后面
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
remove()
//index 后面的数据全部往前移动一位
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//相对于前面的remove(int index)这里省略了index范围检查和返回删除数据
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
clear()
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
扩容方案:
//扩容程序首先计算准备扩容的大小,等于原始数据长度+原始数据长度/2
//如果扩容长度小于Integer.MAX_VALUE - 8则按照计算的值进行扩容
//如果扩容长度大于则扩容大小为Integer.MAX_VALUE ;
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
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;
}
减容方案:
<span style="font-weight: normal;">public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = Arrays.copyOf(elementData, size);
}
}</span>
内部迭代器:
ArrayList定义了一个迭代器Itr:
/**
该迭代器在生成的时候会存入外部类ArrayList的modCount;该变量定义在AbstractList中;
作用就是在迭代器工作的过程中,不允许外部类ArrayList对object[]数组中的数据进行任何修改;
但是通过迭代器对数据的删除添加没有限制;
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
//删除迭代器刚刚越过的那个数
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
SubList集合
ArrayList还有一个方法用于返回它的子集合:
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
SubList集合是ArrayList的内部类,<span style="color:#ff0000;">该类并没有重新生成一个object数组</span>;
private final AbstractList<E> parent; //外部类的object数组的引用
private final int parentOffset; //外部类的offset
private final int offset;//当前类的offset
int size;//当前类所能访问的最大数据长度
SubList只能访问外部类object数组中的parentOffset+offset到parentOffset+offset+size-1之间的数据