ArrayList源码分析

interface Iterable : //实现此接口使集合对象可以通过迭代器遍历自身元素

  Iterator iterator();

public interface Collection extends Iterable: //接口继承接口使用:extends

int size();

boolean isEmpty();

boolean contains(Object o);

boolean containsAll(Collection c);

boolean add(E e);

boolean addAll(Collection c);

boolean remove(Object o);

boolean removeAll(Collection c);

void clear();

boolean equals(Object o);

int hashCode();

boolean retainAll(Collection c);

Iterator iterator();

Object[] toArray();

T[] toArray(T[] a);

public interface List extends Collection

int size();

boolean isEmpty();

boolean contains(Object o);

Iterator iterator();

Object[] toArray();

T[] toArray(T[] a);

boolean add(E e);

boolean remove(Object o);

boolean removeAll(Collection c);

boolean containsAll(Collection c);

boolean addAll(Collection c);

boolean addAll(int index, Collection c);

boolean retainAll(Collection c);

void clear();

boolean equals(Object o);

int hashCode();

E get(int index);

E set(int index, E element);

void add(int index, E element);

E remove(int index);

int indexOf(Object o);

int lastIndexOf(Object o);

ListIterator listIterator();

ListIterator listIterator(int index);

List subList(int fromIndex, int toIndex);

public class ArrayList extends AbstractList

implements List, RandomAccess, Cloneable, java.io.Serializable

private transient Object[] elementData;//实则为数组

        private int size;

public ArrayList() {//默认长度10

this(10);

}

public ArrayList(Collection c) {

elementData = c.toArray(); //现在elementData已经可能不是Object[]

size = elementData.length;

// c.toArray might (incorrectly) not return Object[] (see 6260652)

if (elementData.getClass() != Object[].class)

//将另一个数组copy到当前数组

                    elementData = Arrays.copyOf(elementData, size, Object[].class);

}

public void trimToSize() {

modCount++;

int oldCapacity = elementData.length;//当前长度

                if (size < oldCapacity) {

//当前数组长度大于设定的size,将超过size部分的元素截掉

                    elementData = Arrays.copyOf(elementData, size);

}

}

//数组扩容/收缩[自我拷贝]

public static T[] copyOf(T[] original, int newLength) {

return (T[]) copyOf(original, newLength, original.getClass());

}

public boolean isEmpty() {

return size == 0;//是否为空,即大小是否为0

}

public boolean contains(Object o) {

return indexOf(o) >= 0;//contains()底层调用的是indexOf()

}

public Object clone() {

try {

@SuppressWarnings("unchecked")

//浅克隆:只复制了基本类型字段

                        ArrayList v = (ArrayList) super.clone();//???为什么克隆之后还要将内容拷贝过去

                        //深克隆:引用类型字段也复制

                        v.elementData = Arrays.copyOf(elementData, size);

v.modCount = 0;

return v;

} catch (CloneNotSupportedException e) {

// this shouldn't happen, since we are Cloneable

throw new InternalError();

}

}

public Object[] toArray() {

return Arrays.copyOf(elementData, size);

}

public T[] toArray(T[] a) {

if (a.length < size) //小于elementData长度时,通过Arrays.copyOf()复制出一个新的数组

                        return (T[]) Arrays.copyOf(elementData, size, a.getClass());

System.arraycopy(elementData, 0, a, 0, size);

if (a.length > size)

a[size] = null;

return a;

}

//private:同类, default:同包, protected:不同包子类, public:公共

            E elementData(int index) {

return (E) elementData[index];

}

public E get(int index) {

rangeCheck(index); //throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

return elementData(index);

}

public E set(int index, E element) {

rangeCheck(index);

E oldValue = elementData(index);

elementData[index] = element;

return oldValue;

}

public boolean add(E e) {

ensureCapacityInternal(size + 1);  // Increments modCount!!

elementData[size++] = e;

return true;

}

private void ensureCapacityInternal(int minCapacity) {

modCount++;

// overflow-conscious code

if (minCapacity - elementData.length > 0)//elementData.length:这个不是数组实际长度??

                        grow(minCapacity);//超出容量,扩容

                }

//防溢出

            private void grow(int minCapacity) {

// overflow-conscious code

int oldCapacity = elementData.length;

// >>位运算,右移动一位。 整体相当于newCapacity =oldCapacity + 0.5 * oldCapacity

// jdk1.7采用位运算比以前的计算方式更快

                    int newCapacity = oldCapacity + (oldCapacity >> 1);

if (newCapacity - minCapacity < 0) //这里为什么不直接用<【minCapacity可能为负数】

                        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);//自我拷贝

                }

public void add(int index, E element) {

rangeCheckForAdd(index);

ensureCapacityInternal(size + 1);  // Increments modCount!!

//将index之后的元素,拷到index+1的位置之后

                    System.arraycopy(elementData, index, elementData, index + 1,

size - index);

//空出index的位置,将新元素加进来

                    elementData[index] = element;

size++;

}

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; // Let gc do its work

return oldValue;

}

public boolean addAll(Collection 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;

}

public boolean addAll(int index, Collection c) {

rangeCheckForAdd(index);

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacityInternal(size + numNew);  // Increments modCount

int numMoved = size - index;

if (numMoved > 0)

System.arraycopy(elementData, index, elementData, index + numNew,

numMoved);

System.arraycopy(a, 0, elementData, index, numNew);

size += numNew;

return numNew != 0;

}

protected void removeRange(int fromIndex, int toIndex) {

modCount++;

int numMoved = size - toIndex;

System.arraycopy(elementData, toIndex, elementData, fromIndex,

numMoved);

// Let gc do its work

int newSize = size - (toIndex-fromIndex);

while (size != newSize)

elementData[--size] = null;

}

private class Itr implements Iterator {

int cursor;      // index of next element to return

int lastRet = -1; // index of last element returned; -1 if no such

//将arrayList被修改的次数记录下来,如果Itr遍历过程中,modCount被修改,直接抛出异常

                        int expectedModCount = modCount;

public void remove() {

if (lastRet < 0)

throw new IllegalStateException();

checkForComodification();

try {

/*静态内部类的话,只能new一个外部类对象了。

若是实例内部类,可以使用类名限定

例子:

                              (外部类类名)OuterClass.this就可以得到外部类的引用了。*/

ArrayList.this.remove(lastRet);

cursor = lastRet;

lastRet = -1;

//迭代器能过正常删除元素的原因,重置expectedModCount

expectedModCount = modCount;

} catch (IndexOutOfBoundsException ex) {

throw new ConcurrentModificationException();

}

}

你可能感兴趣的:(ArrayList源码分析)