java.util.ArrayList

java.util.ArrayList

api

List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。

具体介绍见 http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/ArrayList.html

construct

ArrayList是一个顺序列表,是对一个数组的封装

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

	 /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

elementData数组是存储数据的容器,size表示当前存储元素的个数

ArrayList有三个构造函数

  • ArrayList()
    默认构造函数,lazey的思想,将elementData设置为一个空数组,在add()时初始化大小为10
  • ArrayList(int initialCapacity)将elementData初始化为固定指定大小this.elementData = new Object[initialCapacity]
  • ArrayList(Collection<? extends E> c)
    用另一个集合的底层数组来构成新的ArrayList,elementData = c.toArray();

Collection.toArray()方法返回该集合的底层数组(ArrayList也是一个集合,实现了interface Collection)

Collection.toArray()具体介绍
http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/Collection.html#toArray()

构造函数ArrayList(Collection<? extends E> c)中还有一段代码,是为了处理bug 6260652

        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);

因为c.toArray返回的可能不是Object[].class类型,例如返回了String[].class类型,这里用Arrays.copyOf重新复制了一下数组,并且作了类型转化

reference http://www.zhihu.com/question/26603565

主要方法实现

add

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);扩充容量  // Increments modCount!!
        elementData[size++] = e;//放入元素到数组
        return true;
    }

get

原文地址:https://www.cnblogs.com/CHzero/p/5557908.html