ArrayList源码

  • ArrayList底层是一个长度可以动态增长的Object数组(StringBuilder底层是一个长度可以动态增长的char数组)
  • 接口可以一个方法也不提供,如RandomAccess, Cloneable, java.io.Serializable
  • jdk1.7中,使用无参构造方法创建ArrayList对象时,默认底层数组长度10
  • jdk1.8中,使用无参构造方法创建ArrayList对象时,默认底层数组长度0
  • 第一次添加元素,容量不足时会进行扩容
  • arrayList.add(1)--添加元素:容量不足时扩容,默认扩容50%,如果扩容50%后还不足容纳新增元素,就扩容为能容纳新增元素的最小数量
  • ArrayList提供了一个内部类Itr,实现了Iterator接口,实现对集合元素的遍历。使用内部类可以直接访问外部类的成员变量
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    private static final int DEFAULT_CAPACITY = 10;//默认容量10

    private static final Object[] EMPTY_ELEMENTDATA = {};//空数组
    
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};//默认空数组

    transient Object[] elementData; //数组
    
    private int size;
   
     public int size() {
        return size;
    }
    
    public boolean isEmpty() {
        return size == 0;
    }

    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    
    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;
    }
}
创建ArrayList:
    ArrayList arrayList = new ArrayList();

源码:
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//默认空容量数组
    }
创建ArrayList,初始化容量为20:
    ArrayList arrayList = new ArrayList(20);

源码:
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
获取指定下标的元素:
ArrayList arrayList = new ArrayList();
   arrayList.get(1);//获取下标是1的元素
源码:
public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
 private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
 private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
 E elementData(int index) {
        return (E) elementData[index];
    }
添加元素:容量不足时扩容,默认扩容50%,如果扩容50%后还不足容纳新增元素,就扩容为能容纳新增元素的最小数量
    arrayList.add(1);
源码:
 public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
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);
    }
内部类Itr:
public Iterator<E> iterator() {
        return new 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;

        Itr() {}

        public boolean hasNext() {
            return cursor != size;//指针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];//返回指定下标的元素
        }
}

ArrayList源码

上一篇:Celery异步任务框架


下一篇:MVVMLight ViewModel to View 消息传递