ArrayList源码分析

来源:互联网 发布:故宫太和殿su模型数据 编辑:程序博客网 时间:2024/05/21 17:15
 ArrayList是List接口的可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。
   每个ArrayList实例都有一个容量,该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向ArrayList中不断添加元素,其容量也自动增长。自动增长会带来数据向新数组的重新拷贝,因此,如果可预知数据量的多少,可在构造ArrayList时指定其容量。在添加大量元素前,应用程序也可以使用ensureCapacity操作来增加ArrayList实例的容量,这可以减少递增式再分配的数量。 

   注意,此实现不是同步的。如果多个线程同时访问一个ArrayList实例,而其中至少一个线程从结构上修改了列表,那么它必须保持外部同步。

   java集合框架示意图如下:

   其中ArrayList与Collection的关系:


    ArrayList的继承关系如下:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. java.lang.Object  
  2.    ↳     java.util.AbstractCollection<E>  
  3.          ↳     java.util.AbstractList<E>  
  4.                ↳     java.util.ArrayList<E>  
  5.   
  6. public class ArrayList<E> extends AbstractList<E>  
  7.         implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}  

    ArrayList继承了AbstractList,实现了List。它是一个数组队列,相当于动态数组。提供了相关的添加、删除、修改和遍历等功能。

    ArrayList实现了RandomAccess接口,即提供了随机访问功能。RandomAccess是java中用来被List实现,为List提供快速访问功能的。在ArrayList中,我们即可以通过元素的序号来快速获取元素对象,这就是快速随机访问。下文会比较List的“快速随机访问”和使用“Iterator迭代器访问”的效率。

    ArrayList实现了Cloneable接口,即覆盖了函数clone(),能被克隆。

    ArrayList实现了java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。

    和Vector不同,ArrayList中的操作是非线程安全的。所以建议在单线程中使用ArrayList,在多线程中选择Vector或者CopyOnWriteArrayList。

    我们先总览下ArrayList的构造函数和API

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /****************** ArrayList中的构造函数 ***************/  
  2. // 默认构造函数  
  3. ArrayList()  
  4.   
  5. // capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。  
  6. ArrayList(int capacity)  
  7.   
  8. // 创建一个包含collection的ArrayList  
  9. ArrayList(Collection<? extends E> collection)  
  10.   
  11. /****************** ArrayList中的API ********************/  
  12. // Collection中定义的API  
  13. boolean             add(E object)  
  14. boolean             addAll(Collection<? extends E> collection)  
  15. void                clear()  
  16. boolean             contains(Object object)  
  17. boolean             containsAll(Collection<?> collection)  
  18. boolean             equals(Object object)  
  19. int                 hashCode()  
  20. boolean             isEmpty()  
  21. Iterator<E>         iterator()  
  22. boolean             remove(Object object)  
  23. boolean             removeAll(Collection<?> collection)  
  24. boolean             retainAll(Collection<?> collection)  
  25. int                 size()  
  26. <T> T[]             toArray(T[] array)  
  27. Object[]            toArray()  
  28. // AbstractCollection中定义的API  
  29. void                add(int location, E object)  
  30. boolean             addAll(int location, Collection<? extends E> collection)  
  31. E                   get(int location)  
  32. int                 indexOf(Object object)  
  33. int                 lastIndexOf(Object object)  
  34. ListIterator<E>     listIterator(int location)  
  35. ListIterator<E>     listIterator()  
  36. E                   remove(int location)  
  37. E                   set(int location, E object)  
  38. List<E>             subList(int start, int end)  
  39. // ArrayList新增的API  
  40. Object               clone()  
  41. void                 ensureCapacity(int minimumCapacity)  
  42. void                 trimToSize()  
  43. void                 removeRange(int fromIndex, int toIndex)  
    ArrayList包含了两个重要的对象:elementData和size。

    elementData是Object[]类型的数组,它保存了添加到ArrayList中的元素。实际上,elementData是一个动态数组,我们能通过ArrayList(int initialCapacity)来执行它的初始容量为initialCapacity。如果通过不含参数的构造函数来创建ArrayList,则elementData是一个空数组(后面会调整其大小)。elementData数组的大小会根据ArrayList容量的增长而动态的增长,具体见下面的源码。

    size则是动态数组实际的大小。

ArrayList的实现:

   对于ArrayList而言,它实现List接口、底层使用数组保存所有元素。其操作基本上是对数组的操作。下面我们来分析ArrayList的源代码:

   1) 底层使用数组实现:

Java代码  收藏代码
  1. private transient Object[] elementData;  

    2) 构造方法: 
   ArrayList提供了三种方式的构造器,可以构造一个默认初始容量为10的空列表、构造一个指定初始容量的空列表以及构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。

Java代码  收藏代码
  1. public ArrayList() {  
  2.     this(10);  
  3. }  
  4.   
  5. public ArrayList(int initialCapacity) {  
  6.     super();  
  7.     if (initialCapacity < 0)  
  8.         throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);  
  9.     this.elementData = new Object[initialCapacity];  
  10. }  
  11.   
  12. public ArrayList(Collection<? extends E> c) {  
  13.     elementData = c.toArray();  
  14.     size = elementData.length;  
  15.     // c.toArray might (incorrectly) not return Object[] (see 6260652)  
  16.     if (elementData.getClass() != Object[].class)  
  17.         elementData = Arrays.copyOf(elementData, size, Object[].class);  
  18. }  

    3) 存储: 
   ArrayList提供了set(int index, E element)、add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)这些添加元素的方法。下面我们一一讲解:

Java代码  收藏代码
  1. // 用指定的元素替代此列表中指定位置上的元素,并返回以前位于该位置上的元素。  
  2. public E set(int index, E element) {  
  3.     RangeCheck(index);  
  4.   
  5.     E oldValue = (E) elementData[index];  
  6.     elementData[index] = element;  
  7.     return oldValue;  
  8. }  
Java代码  收藏代码
  1. // 将指定的元素添加到此列表的尾部。  
  2. public boolean add(E e) {  
  3.     ensureCapacity(size + 1);   
  4.     elementData[size++] = e;  
  5.     return true;  
  6. }  
Java代码  收藏代码
  1. // 将指定的元素插入此列表中的指定位置。  
  2. // 如果当前位置有元素,则向右移动当前位于该位置的元素以及所有后续元素(将其索引加1)。  
  3. public void add(int index, E element) {  
  4.     if (index > size || index < 0)  
  5.         throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);  
  6.     // 如果数组长度不足,将进行扩容。  
  7.     ensureCapacity(size+1);  // Increments modCount!!  
  8.     // 将 elementData中从Index位置开始、长度为size-index的元素,  
  9.     // 拷贝到从下标为index+1位置开始的新的elementData数组中。  
  10.     // 即将当前位于该位置的元素以及所有后续元素右移一个位置。  
  11.     System.arraycopy(elementData, index, elementData, index + 1, size - index);  
  12.     elementData[index] = element;  
  13.     size++;  
  14. }  
Java代码  收藏代码
  1. // 按照指定collection的迭代器所返回的元素顺序,将该collection中的所有元素添加到此列表的尾部。  
  2. public boolean addAll(Collection<? extends E> c) {  
  3.     Object[] a = c.toArray();  
  4.     int numNew = a.length;  
  5.     ensureCapacity(size + numNew);  // Increments modCount  
  6.     System.arraycopy(a, 0, elementData, size, numNew);  
  7.     size += numNew;  
  8.     return numNew != 0;  
  9. }  
Java代码  收藏代码
  1. // 从指定的位置开始,将指定collection中的所有元素插入到此列表中。  
  2. public boolean addAll(int index, Collection<? extends E> c) {  
  3.     if (index > size || index < 0)  
  4.         throw new IndexOutOfBoundsException(  
  5.             "Index: " + index + ", Size: " + size);  
  6.   
  7.     Object[] a = c.toArray();  
  8.     int numNew = a.length;  
  9.     ensureCapacity(size + numNew);  // Increments modCount  
  10.   
  11.     int numMoved = size - index;  
  12.     if (numMoved > 0)  
  13.         System.arraycopy(elementData, index, elementData, index + numNew, numMoved);  
  14.   
  15.     System.arraycopy(a, 0, elementData, index, numNew);  
  16.     size += numNew;  
  17.     return numNew != 0;  
  18. }  

    4) 读取:

Java代码  收藏代码
  1. // 返回此列表中指定位置上的元素。  
  2. public E get(int index) {  
  3.     RangeCheck(index);  
  4.   
  5.     return (E) elementData[index];  
  6. }  

    5) 删除: 
   ArrayList提供了根据下标或者指定对象两种方式的删除功能。如下:

Java代码  收藏代码
  1. // 移除此列表中指定位置上的元素。  
  2. public E remove(int index) {  
  3.     RangeCheck(index);  
  4.   
  5.     modCount++;  
  6.     E oldValue = (E) elementData[index];  
  7.   
  8.     int numMoved = size - index - 1;  
  9.     if (numMoved > 0)  
  10.         System.arraycopy(elementData, index+1, elementData, index, numMoved);  
  11.     elementData[--size] = null// Let gc do its work  
  12.   
  13.     return oldValue;  
  14. }  
Java代码  收藏代码
  1. // 移除此列表中首次出现的指定元素(如果存在)。这是应为ArrayList中允许存放重复的元素。  
  2. public boolean remove(Object o) {  
  3.     // 由于ArrayList中允许存放null,因此下面通过两种情况来分别处理。  
  4.     if (o == null) {  
  5.         for (int index = 0; index < size; index++)  
  6.             if (elementData[index] == null) {  
  7.                 // 类似remove(int index),移除列表中指定位置上的元素。  
  8.                 fastRemove(index);  
  9.                 return true;  
  10.             }  
  11. else {  
  12.     for (int index = 0; index < size; index++)  
  13.         if (o.equals(elementData[index])) {  
  14.             fastRemove(index);  
  15.             return true;  
  16.         }  
  17.     }  
  18.     return false;  
  19. }  

    注意:从数组中移除元素的操作,也会导致被移除的元素以后的所有元素的向左移动一个位置。
   6) 调整数组容量: 
   从上面介绍的向ArrayList中存储元素的代码中,我们看到,每当向数组中添加元素时,都要去检查添加后元素的个数是否会超出当前数组的长度,如果超出,数组将会进行扩容,以满足添加数据的需求。数组扩容通过一个公开的方法ensureCapacity(int minCapacity)来实现。在实际添加大量元素前,我也可以使用ensureCapacity来手动增加ArrayList实例的容量,以减少递增式再分配的数量。

Java代码  收藏代码
  1. public void ensureCapacity(int minCapacity) {  
  2.     modCount++;  
  3.     int oldCapacity = elementData.length;  
  4.     if (minCapacity > oldCapacity) {  
  5.         Object oldData[] = elementData;  
  6.         int newCapacity = (oldCapacity * 3)/2 + 1;  
  7.             if (newCapacity < minCapacity)  
  8.                 newCapacity = minCapacity;  
  9.       // minCapacity is usually close to size, so this is a win:  
  10.       elementData = Arrays.copyOf(elementData, newCapacity);  
  11.     }  
  12. }  

   从上述代码中可以看出,数组进行扩容时,会将老数组中的元素重新拷贝一份到新的数组中,每次数组容量的增长大约是其原容量的1.5倍。这种操作的代价是很高的,因此在实际使用时,我们应该尽量避免数组容量的扩张。当我们可预知要保存的元素的多少时,要在构造ArrayList实例时,就指定其容量,以避免数组扩容的发生。或者根据实际需求,通过调用ensureCapacity方法来手动增加ArrayList实例的容量。
   ArrayList还给我们提供了将底层数组的容量调整为当前列表保存的实际元素的大小的功能。它可以通过trimToSize方法来实现。代码如下:

Java代码  收藏代码
  1. public void trimToSize() {  
  2.     modCount++;  
  3.     int oldCapacity = elementData.length;  
  4.     if (size < oldCapacity) {  
  5.         elementData = Arrays.copyOf(elementData, size);  
  6.     }  
  7. }  

   7) Fail-Fast机制: 
ArrayList也采用了快速失败的机制,通过记录modCount参数来实现。在面对并发的修改时,迭代器很快就会完全失败,而不是冒着在将来某个不确定时间发生任意不确定行为的风险。
   

.ArrayList遍历方式

    ArrayList支持三种遍历方式,下面我们逐个讨论:

    1). 通过迭代器遍历。即Iterator迭代器。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Integer value = null;  
  2. Iterator it = list.iterator();  
  3. while (it.hasNext()) {  
  4.     value = (Integer)it.next();  
  5. }  
    2). 随机访问,通过索引值去遍历。由于ArrayList实现了RandomAccess接口,所以它支持通过索引值去随机访问元素。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Integer value = null;  
  2. int size = list.size();  
  3. for (int i = 0; i < size; i++) {  
  4.     value = (Integer)list.get(i);          
  5. }  
   3). 通过for循环遍历。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Integer value = null;  
  2. for (Integer integ : list) {  
  3.     value = integ;  
  4. }  
        下面写了一个测试用例,比较这三种遍历方式的效率:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.util.*;  
  2.   
  3. /* 
  4.  * @description ArrayList三种遍历方式效率的测试 
  5.  * @author eson_15 
  6.  */  
  7. public class ArrayListRandomAccessTest {  
  8.   
  9.     public static void main(String[] args) {  
  10.         List<Integer> list = new ArrayList<Integer>();  
  11.         for (int i=0; i<500000; i++)  
  12.             list.add(i);  
  13.         isRandomAccessSupported(list);//判断是否支持RandomAccess  
  14.         iteratorThroughRandomAccess(list) ;  
  15.         iteratorThroughIterator(list) ;  
  16.         iteratorThroughFor(list) ;  
  17.       
  18.     }  
  19.   
  20.     private static void isRandomAccessSupported(List<Integer> list) {  
  21.         if (list instanceof RandomAccess) {  
  22.             System.out.println("RandomAccess implemented!");  
  23.         } else {  
  24.             System.out.println("RandomAccess not implemented!");  
  25.         }  
  26.   
  27.     }  
  28.   
  29.     public static void iteratorThroughRandomAccess(List<Integer> list) {  
  30.   
  31.         long startTime;  
  32.         long endTime;  
  33.         startTime = System.currentTimeMillis();  
  34.         for (int i=0; i<list.size(); i++) {  
  35.             list.get(i);  
  36.         }  
  37.         endTime = System.currentTimeMillis();  
  38.         long interval = endTime - startTime;  
  39.         System.out.println("RandomAccess遍历时间:" + interval+" ms");  
  40.     }  
  41.   
  42.     public static void iteratorThroughIterator(List<Integer> list) {  
  43.   
  44.         long startTime;  
  45.         long endTime;  
  46.         startTime = System.currentTimeMillis();  
  47.         for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {  
  48.             it.next();  
  49.         }  
  50.         endTime = System.currentTimeMillis();  
  51.         long interval = endTime - startTime;  
  52.         System.out.println("Iterator遍历时间:" + interval+" ms");  
  53.     }  
  54.   
  55.   
  56.     @SuppressWarnings("unused")  
  57.     public static void iteratorThroughFor(List<Integer> list) {  
  58.   
  59.         long startTime;  
  60.         long endTime;  
  61.         startTime = System.currentTimeMillis();  
  62.         for(Object obj : list)  
  63.             ;  
  64.         endTime = System.currentTimeMillis();  
  65.         long interval = endTime - startTime;  
  66.         System.out.println("For循环遍历时间:" + interval+" ms");  
  67.     }  
  68. }  
    每次执行的结果会有一点点区别,在这里我统计了6次执行结果,见下表:

 

RandomAccess(ms)

Iterator(ms)

For(ms)

第一次

5

8

7

第二次

4

7

7

第三次

5

8

10

第四次

5

7

6

第五次

5

8

7

第六次

5

7

6

平均

4.8

7.5

7.1

    由此可见,遍历ArrayList时,使用随机访问(即通过索引号访问)效率最高,而使用迭代器的效率最低。

toArray()异常问题

    当我们调用ArrayList中的toArray()方法时,可能会遇到"java.lang.ClassCastException"异常的情况,下面来讨论下出现的原因:

    ArrayList中提供了2个toArray()方法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Object[] toArray()  
  2. <T> T[] toArray(T[] contents)  
    调用toArray()函数会抛出"java.lang.ClassCastException"异常,但是调用toArray(T[] contents)能正常返回T[]。toArray()会抛出异常是因为toArray()返回的是Object[]数组,将Object[]转换为其它类型(比如将Object[]转换为Integer[])则会抛出"java.lang.ClassCastException"异常,因为java不支持向下转型。解决该问题的办法是调用<T> T[] toArray(T[] contents),而不是Object[] toArray()。

    调用<T> T[] toArray(T[] contents)返回T[]可以通过以下几种方式实现:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // toArray(T[] contents)调用方式一  
  2. public static Integer[] vectorToArray1(ArrayList<Integer> v) {  
  3.     Integer[] newText = new Integer[v.size()];  
  4.     v.toArray(newText);  
  5.     return newText;  
  6. }  
  7.   
  8. // toArray(T[] contents)调用方式二。最常用! 
  9. public static Integer[] vectorToArray2(ArrayList<Integer> v) {  
  10.     Integer[] newText = (Integer[])v.toArray(new Integer[v.size()]);  
  11.     return newText;  
  12. }  
  13.   
  14. // toArray(T[] contents)调用方式三  
  15. public static Integer[] vectorToArray3(ArrayList<Integer> v) {  
  16.     Integer[] newText = new Integer[v.size()];  
  17.     Integer[] newStrings = (Integer[])v.toArray(newText);  
  18.     return newStrings;  
  19. }  
    三种方式都大同小异。转自:http://zhangshixi.iteye.com/blog/674856

同时参考:http://blog.csdn.net/eson_15/article/details/51121833

0 0