在日常工作中,在我们的项目中经常需要使用到List,大部分都是使用List的实现类ArrayList。因为使用List非常方便,他自己会根据数据量的大小自动调整ArrayList的大小,并且访问也非常方便。下面我将和大家讨论一下ArrayList是怎么实现的,只有你了解的ArrayList的内部实现原理,才能应用自如。将它应用到适当的地方,使ArrayList功能得到最大限度的使用。
1、怎样获取ArrayList的源代码
在你的%java_home%目录下面存在src.zip文件,使用解压工具进行解压,然后在%java_home%srcjavautil目录下面找到ArrayList类的java文件,然后使用IDE或具有语法高亮的工具打开。
2、ArrayList继承体系
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {...}
从上面ArrayList的部分源码发现:
a、继承了AbstractList抽象类
此类提供List接口的基础实现,以最大限度地减少实现“随机访问”数据存储(如数组)支持的该接口所需的工作。对于连续的访问数据(如链表),应优先使用 AbstractSequentialList,而不是此类。
b、实现了List接口
是所有List集合的父接口,提供了List集合的基本方法,如:获取元素、添加元素、清空等方法签名。
c、实现了RandomAccess接口
是一个标记接口,用来表明其List支持快速(通常是固定时间)随机访问。此接口的主要目的是允许一般的算法更改其行为,从而在将其应用到随机或连续访问列表时能提供良好的性能。
将操作随机访问列表的最佳算法(如:ArrayList)应用到连续访问列表(如:LinkedList)时,可产生二次项的行为。如果将某个算法应用到连续访问列表,那么在应用可能提供较差性能的算法前,鼓励使用一般的列表算法检查给定列表是否为此接口的一个 instanceof,如果需要保证可接受的性能,还可以更改其行为。
现在已经认识到,随机和连续访问之间的区别通常是模糊的。例如,如果列表很大时,某些List实现提供渐进的线性访问时间,但实际上是固定的访问时间。这样的List实现通常应该实现此接口。实际经验证明,如果是下列情况,则List实现应该实现此接口,即对于典型的类实例而言,此循环:
for (int i=0, n=list.size(); i < n; i++) list.get(i);
的运行速度要快于以下循环:
for (Iterator i=list.iterator(); i.hasNext(); ) i.next();
d、实现了Cloneable接口
此类实现了Cloneable 接口,以指示Object.clone()方法可以合法地对该类实例进行按字段复制。如果在没有实现Cloneable接口的实例上调用Object的clone 方法,则会导致抛出 CloneNotSupportedException 异常。
e、实现了序列化Serializable接口
实现此接口可以启动该类的序列化功能。序列化的类可以通过IO保存到磁盘,进行网络传输等。该接口也是标识接口。
3、ArrayList内部实现
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. */ // 用来存放ArrayList中的数据 private transient Object[] elementData; /** * The size of the ArrayList (the number of elements it contains). * * @serial */ // 记录了ArrayList的大小 private int size;
通过上面提供的几个成员变量可以知道ArrayList内部使用了一个Object数组来存放数据并且通过一个size属性来保存ArrayList中元素的个数。
下面是ArrayList的3个构造函数的实现源码:
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @exception IllegalArgumentException if the specified initial capacity * is negative */ public ArrayList(int initialCapacity) { super(); // ArrayList的初始容量不能小于0。如果小于0,则抛出错误。 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); // 初始化ArrayList内部数组的大小 this.elementData = new Object[initialCapacity]; } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { // ArrayList默认大小是10 this(10); } /** * 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(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) // c.toArray可能不反悔Object数组,因此使用Arrays的copyOf方法返回目标c集合的一个Object // 数组副本来覆盖elementData if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
从上面的构造方法可以得知,ArrayList默认构造方法设置数组大小为10。
下面是ArrayList的add、get和rmove方法(添加、获取、移除方法):
/** * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ // 计算当前ArrayList的容量是否足够容纳给定的数据,如果不够则增大ArrayList的容量 public void ensureCapacity(int minCapacity) { modCount++; // ArrayList的容量 int oldCapacity = elementData.length; // 如果新增元素后的容量大于ArrayList当前容量,则将ArrayList扩大 if (minCapacity > oldCapacity) { Object oldData[] = elementData; // 计算ArrayList的新容量 int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: // 将ArrayList历史数据拷贝到分配新容量的数组中去 elementData = Arrays.copyOf(elementData, newCapacity); } } /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { // 计算容量 ensureCapacity(size + 1); // Increments modCount!! // 将元素添加到elementData数组且将size加1 elementData[size++] = e; return true; } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { // 范围检查 RangeCheck(index); // 根据下标从数组中获取数据 return (E) elementData[index]; } /** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) { // 范围检查 RangeCheck(index); modCount++; // 取出被删除的元素 E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) // 将删除元素后面的元素向前移动,如: // 删除a[2],即删除22,删除需要将22后面的13和15向前移动([10, 19, 13, 15]), // a = [10, 19, 22, 13, 15] System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; }
4、总结
根据上面ArrayList中几个常见方法,get、add、remove可以得知ArrayList内部使用的是Object数组。在JDK新版本中使用了泛型来执行ArrayList内部数组的类型。由数组的特性可以总结如下:
a、ArrayList进行数据访问是非常快的,因为数组是按下表进行获取(即按照地址去取数据)。
b、ArrayList进行移除操作是非常耗时的,因为数组要将删除元素后面的所有元素相前面移动。
c、在元素大于10个的时候指定一个合理的大小也是很重要的,这样ArrayList就不会经常去重新调整容量。