简述:

  • ArrayList可以理解为动态数组,与Java中的数组相比,它的容量能动态增长。超出限制时会增加50%容量,用System.arraycopy()复制到新的数组中,因此最好能给出数组大小的预估值;
  • 容量大小也可以在程序中通过ensureCapacity(int minCapacity)方法来调整;
  • 默认第一次插入元素时创建大小为10的数组(注意,是在插入元素时,而不是new ArrayList时);
  • ArrayList继承了AbstractList,实现了List;实现了RandomAccess接口,即提供了随机访问功能;实现了Cloneable接口,覆盖了clone()方法,能被克隆;实现了Serializable接口,支持序列化;

数据结构:

  使用Object数组实现

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

构造方法:

  提供了三种方式的构造器:

  1. public ArrayList() 可以构造一个空列表;
  2. public ArrayList(int initialCapacity) 构造一个指定初始容量的空列表;
  3. public ArrayList(Collection<? extends E> c) 构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列;
 1 /**
 2      * Constructs an empty list with the specified initial capacity.
 3      * @param  initialCapacity  the initial capacity of the list
 4      * @throws IllegalArgumentException if the specified initial capacity
 5      *         is negative
 6      */
 7     public ArrayList(int initialCapacity) {
 8         if (initialCapacity > 0) {
 9             this.elementData = new Object[initialCapacity];
10         } else if (initialCapacity == 0) {
11             this.elementData = EMPTY_ELEMENTDATA;
12         } else {
13             throw new IllegalArgumentException("Illegal Capacity: "+
14                                                initialCapacity);
15         }
16     }
17     /**
18      * Constructs an empty list with an initial capacity of ten.
19      */
20     public ArrayList() {
21         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
22     }
23     /**
24      * Constructs a list containing the elements of the specified
25      * collection, in the order they are returned by the collection's
26      * iterator.
27      * @param c the collection whose elements are to be placed into this list
28      * @throws NullPointerException if the specified collection is null
29      */
30     public ArrayList(Collection<? extends E> c) {
31         elementData = c.toArray();
32         if ((size = elementData.length) != 0) {
33             // c.toArray might (incorrectly) not return Object[] (see 6260652)
34             if (elementData.getClass() != Object[].class)
35                 elementData = Arrays.copyOf(elementData, size, Object[].class);
36         } else {
37             // replace with empty array.
38             this.elementData = EMPTY_ELEMENTDATA;
39         }
40     }
View Code

相关文章: