项目中经常使用arraylist,知道到怎么使用,但是还未看过它的底层实现原理,现在结合jdkapi以及源码分析下。
一、ArrayList概述
从api上可以看出,ArrayList是实现List接口的“动态数组”,所谓动态就是它的大小是可变的。实现了所有可选列表操作,并允许包括 null 在内的所有元素。
注意,ArrayList实现不是同步的。如果多个线程同时访问一个ArrayList实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。所以为了保证同步,最好的办法是在创建时完成,以防止意外对列表进行不同步的访问:
List list = Collections.synchronizedList(new ArrayList(…));
二、源码解析
类的定义:
1 public class ArrayList<E> extends AbstractList<E> 2 implements List<E>, RandomAccess, Cloneable, java.io.Serializable 3 { 4 private static final long serialVersionUID = 8683452581122892189L; 5 6 /** 7 * The array buffer into which the elements of the ArrayList are stored. 8 * The capacity of the ArrayList is the length of this array buffer. 9 */ 10 private transient Object[] elementData; 11 12 /** 13 * The size of the ArrayList (the number of elements it contains). 14 * 15 * @serial 16 */ 17 private int size; 18 19 /** 20 * Constructs an empty list with the specified initial capacity. 21 * 22 * @param initialCapacity the initial capacity of the list 23 * @throws IllegalArgumentException if the specified initial capacity 24 * is negative 25 */ 26 public ArrayList(int initialCapacity) { 27 super(); 28 if (initialCapacity < 0) 29 throw new IllegalArgumentException("Illegal Capacity: "+ 30 initialCapacity); 31 this.elementData = new Object[initialCapacity]; 32 } 33 34 /** 35 * Constructs an empty list with an initial capacity of ten. 36 */ 37 public ArrayList() { 38 this(10); 39 } 40 41 /** 42 * Constructs a list containing the elements of the specified 43 * collection, in the order they are returned by the collection's 44 * iterator. 45 * 46 * @param c the collection whose elements are to be placed into this list 47 * @throws NullPointerException if the specified collection is null 48 */ 49 public ArrayList(Collection<? extends E> c) { 50 elementData = c.toArray(); 51 size = elementData.length; 52 // c.toArray might (incorrectly) not return Object[] (see 6260652) 53 if (elementData.getClass() != Object[].class) 54 elementData = Arrays.copyOf(elementData, size, Object[].class); 55 }
1、实现接口
arraylist实现了List、RandomAccess、Cloneable、Serializable接口,继承AbstractList类。在JDK中,RandomAccess接口是一个空接口,所以它没有实际意义,就是一个标记,标记这个类支持快速随机访问,所以,arrayList是支持随机访问的,