七叶笔记 » java编程 » java中的ArrayList集合的初始化方式

java中的ArrayList集合的初始化方式

概述

ArrayList是一个以动态数组为基础实现的非线程安全的集合,ArrayList的元素可以为空、可以重复,同时又是有序的(读取和存放的顺序一致 )。

ArrayList继承AbstractList,实现了ListRandomAccess(可以快速访问)、Cloneable(可以被克隆)、java.io.Serializable(支持序列化)

更多免费相关视频推荐:java视频

ArrayList的初始化方式有三种:

1、无参构造,默认长度为10,是我们使用的最多的一种初始化方式:

/**  * Constructs an empty list with an initial capacity of ten.  */  public ArrayList() {      this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;  }

这个时候,我们从源码中可以看到,里面只有一行代码:this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA,那么定义的DEFAULTCAPACITY_EMPTY_ELEMENTDATA可以在源码中找到:

/**  * Shared empty array instance used for default sized empty instances. We  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when  * first element is added.  */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

通过注释可以得知,源码中定义了一个空的数组作为默认的大小,并且在第一个元素添加进来的时候再确定把数组扩充多少,这段逻辑会在接下来添加元素部分作出解释。

2、指定初始化长度:

/**  * Constructs an empty list with the specified initial capacity.  * @param  initialCapacity  the initial capacity of the list  * @throws IllegalArgumentException if the specified initial capacity  *         is negative  */  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);     }  }

3、用一个Collection对象来构造

/**     * Constructs a list containing the elements of the specified     * collection, in the order they are returned by the collection's     * iterator.     *     * @param c the collection whose elements are to be placed into this list     * @throws NullPointerException if the specified collection is null     */    public ArrayList(Collection<? extends E> c) {        elementData = c.toArray();        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);        } else {            // replace with empty array.            this.elementData = EMPTY_ELEMENTDATA;        }    }

相关文章教程推荐:java开发入门

相关文章