- ArrayList实现List接口
- RandomAccess接口表示表示ArrayList支持快速随机访问
- 使用动态数组存储数据
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { private static final long serialVersionUID = 8683452581122892189L; /** * 默认初始化容量 */ private static final int DEFAULT_CAPACITY = 10; /** * 可共享的空数组实例,用于空实例对象的创建 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * * 可共享的空数组实例对象,用于默认容量的空实例对象的创建 * 将其与EMPTY_ELEMENTDATA区分开来,以便知道添加第一个元素时需要扩容多少。 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * 存储ArrayList元素的数组,ArraList的容量是数组的长度. * 当elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA时,会在添加第一个元素的时候, * 将容量扩大到DEFAULT_CAPACITY * */ transient Object[] elementData; // non-private to simplify nested class access /** * ArrayList的容量(包含的元素数量)。 * * @serial */ private int size; /** * 构造一个具有指定初始容量的空ArrayList。 * @param initialCapacity 初始化容量 * @throws IllegalArgumentException 如果指定的初始化容量为空 */ 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,初始化容量为10() */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * * 构造一个包含指定集合元素的ArrayList * * @param c 将其元素放置在此列表中的集合 * @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; } } //其他方法 //略 } |
根据上面的定义,ArrayList有如下三种创建方法。
-
构造空的ArrayList
Java
1 2
//创建一个空的ArrayList,默认容量为10 ArrayList<Integer> arrayList1 = new ArrayList<>();
-
指定ArrayList的容量
Java
1 2
//创建一个空的ArrayList,初始容量为20 ArrayList<Integer> arrayList2 = new ArrayList<>(20);
-
传入指定集合元素
Java
1 2 3
//创建一个ArrayList,其内容为collection里面的元素 //如果collection为空会默认创建一个,会创建一个容量为空的ArrayList ArrayList<Integer> arrayList3 = new ArrayList<>(collection);