java集合-ArrayList源码剖析

来源:互联网 发布:python 网页自动签到 编辑:程序博客网 时间:2024/05/16 15:54

转载出处:http://blog.csdn.net/ns_code/article/details/35568011


ArrayList简介

    ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存。

    ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类

    ArrayList实现了Serializable接口,因此它支持序列化,能够通过序列化传输,实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标序号进行快速访问,实现了Cloneable接口,能被克隆。


ArrayList源码剖析

    ArrayList的源码如下(加入了比较详细的注释):

[java]view plaincopy派生到我的代码片
  1. package java.util;    

  2. public class ArrayList extends AbstractList    
  3. implements List, RandomAccess, Cloneable, java.io.Serializable    
  4. {    
  5. // 序列版本号  
  6. private static finallong serialVersionUID = 8683452581122892189L;    

  7. // ArrayList基于该数组实现,用该数组保存数据 
  8. private transient Object[] elementData;    

  9. // ArrayList中实际数据的数量  
  10. privateint size;    

  11. // ArrayList带容量大小的构造函数。  
  12. public ArrayList(int initialCapacity) {    
  13. super();    
  14. if (initialCapacity < 0)    
  15. thrownew IllegalArgumentException("Illegal Capacity: "+    
  16.                                                initialCapacity);    
  17. // 新建一个数组  
  18. this.elementData = new Object[initialCapacity];    
  19.     }    

  20. // ArrayList无参构造函数。默认容量是10。  
  21. public ArrayList() {    
  22. this(10);    
  23.     }    

  24. // 创建一个包含collection的ArrayList  
  25. public ArrayList(Collectionextends E> c) {    
  26.         elementData = c.toArray();    
  27.         size = elementData.length;    
  28. if (elementData.getClass() != Object[].class)    
  29.             elementData = Arrays.copyOf(elementData, size, Object[].class);    
  30.     }    


  31. // 将当前容量值设为实际元素个数  
  32. publicvoid trimToSize() {    
  33.         modCount++;    
  34. int oldCapacity = elementData.length;    
  35. if (size < oldCapacity) {    
  36.             elementData = Arrays.copyOf(elementData, size);    
  37.         }    
  38.     }    


  39. // 确定ArrarList的容量。  
  40. // 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”  
  41. publicvoid ensureCapacity(int minCapacity) {    
  42. // 将“修改统计数”+1,该变量主要是用来实现fail-fast机制的  
  43.         modCount++;    
  44. int oldCapacity = elementData.length;    
  45. // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”  
  46. if (minCapacity > oldCapacity) {    
  47.             Object oldData[] = elementData;    
  48. int newCapacity = (oldCapacity * 3)/2 + 1;    
  49. //如果还不够,则直接将minCapacity设置为当前容量
  50. if (newCapacity < minCapacity)    
  51.                 newCapacity = minCapacity;    
  52.             elementData = Arrays.copyOf(elementData, newCapacity);    
  53.         }    
  54.     }    

  55. // 添加元素e  
  56. publicboolean add(E e) {    
  57. // 确定ArrayList的容量大小  
  58.         ensureCapacity(size + 1);  // Increments modCount!!  
  59. // 添加e到ArrayList中  
  60.         elementData[size++] = e;    
  61. return true;    
  62.     }    

  63. // 返回ArrayList的实际大小  
  64. publicint size() {    
  65. return size;    
  66.     }    

  67. // ArrayList是否包含Object(o)  
  68. publicboolean contains(Object o) {    
  69. return indexOf(o) >= 0;    
  70.     }    

  71. //返回ArrayList是否为空  
  72. public boolean isEmpty() {    
  73. return size == 0;    
  74.     }    

  75. // 正向查找,返回元素的索引值  
  76. publicint indexOf(Object o) {    
  77. if (o == null) {    
  78. for (int i = 0; i < size; i++)    
  79. if (elementData[i]==null)    
  80. return i;    
  81.             } 
  82. else {    
  83. for (int i = 0; i < size; i++)    
  84. if (o.equals(elementData[i]))    
  85. return i;    
  86.             }    
  87. return -1;    
  88.         }    

  89. // 反向查找,返回元素的索引值  
  90. publicint lastIndexOf(Object o) {    
  91. if (o == null) {    
  92. for (int i = size-1; i >= 0; i--)    
  93. if (elementData[i]==null)    
  94. return i;    
  95.         } else {    
  96. for (int i = size-1; i >= 0; i--)    
  97. if (o.equals(elementData[i]))    
  98. return i;    
  99.         }    
  100. return -1;    
  101.     }    

  102. // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值  
  103. publicint lastIndexOf(Object o) {    
  104. if (o == null) {    
  105. for (int i = size-1; i >= 0; i--)    
  106. if (elementData[i]==null)    
  107. return i;    
  108.         } else {    
  109. for (int i = size-1; i >= 0; i--)    
  110. if (o.equals(elementData[i]))    
  111. return i;    
  112.         }    
  113. return -1;    
  114.     }    


  115. // 返回ArrayList的Object数组  
  116. public Object[] toArray() {    
  117. return Arrays.copyOf(elementData, size);    
  118.     }    

  119. // 返回ArrayList元素组成的数组
  120. public  T[] toArray(T[] a) {    
  121. // 若数组a的大小 < ArrayList的元素个数;  
  122. // 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中  
  123. if (a.length < size)    
  124. return (T[]) Arrays.copyOf(elementData, size, a.getClass());    

  125. // 若数组a的大小 >= ArrayList的元素个数;  
  126. // 则将ArrayList的全部元素都拷贝到数组a中。  
  127.         System.arraycopy(elementData, 0, a, 0, size);    
  128. if (a.length > size)    
  129.             a[size] = null;    
  130. return a;    
  131.     }    

  132. // 获取index位置的元素值  
  133. public E get(int index) {    
  134.         RangeCheck(index);    

  135. return (E) elementData[index];    
  136.     }    

  137. // 设置index位置的值为element  
  138. public E set(int index, E element) {    
  139.         RangeCheck(index);    

  140.         E oldValue = (E) elementData[index];    
  141.         elementData[index] = element;    
  142. return oldValue;    
  143.     }    

  144. // 将e添加到ArrayList中  
  145. publicboolean add(E e) {    
  146.         ensureCapacity(size + 1);  // Increments modCount!!  
  147.         elementData[size++] = e;    
  148. returntrue;    
  149.     }    

  150. // 将e添加到ArrayList的指定位置  
  151. publicvoid add(int index, E element) {    
  152. if (index > size || index < 0)    
  153. thrownew IndexOutOfBoundsException(    
  154. "Index: "+index+", Size: "+size);    

  155.         ensureCapacity(size+1);  // Increments modCount!!  
  156.         System.arraycopy(elementData, index, elementData, index + 1,    
  157.              size - index);    
  158.         elementData[index] = element;    
  159.         size++;    
  160.     }    

  161. // 删除ArrayList指定位置的元素  
  162. public E remove(int index) {    
  163.         RangeCheck(index);    

  164.         modCount++;    
  165.         E oldValue = (E) elementData[index];    

  166. int numMoved = size - index - 1;    
  167. if (numMoved > 0)    
  168.             System.arraycopy(elementData, index+1, elementData, index,    
  169.                  numMoved);    
  170.         elementData[--size] = null// Let gc do its work  

  171. return oldValue;    
  172.     }    

  173. // 删除ArrayList的指定元素  
  174. publicboolean remove(Object o) {    
  175. if (o == null) {    
  176. for (int index = 0; index < size; index++)    
  177. if (elementData[index] == null) {    
  178.                 fastRemove(index);    
  179. returntrue;    
  180.             }    
  181.         } else {    
  182. for (int index = 0; index < size; index++)    
  183. if (o.equals(elementData[index])) {    
  184.                 fastRemove(index);    
  185. returntrue;    
  186.             }    
  187.         }    
  188. returnfalse;    
  189.     }    


  190. // 快速删除第index个元素  
  191. privatevoid fastRemove(int index) {    
  192.         modCount++;    
  193. int numMoved = size - index - 1;    
  194. // 从"index+1"开始,用后面的元素替换前面的元素。  
  195. if (numMoved > 0)    
  196.             System.arraycopy(elementData, index+1, elementData, index,    
  197.                              numMoved);    
  198. // 将最后一个元素设为null  
  199.         elementData[--size] = null// Let gc do its work  
  200.     }    

  201. // 删除元素  
  202. publicboolean remove(Object o) {    
  203. if (o == null) {    
  204. for (int index = 0; index < size; index++)    
  205. if (elementData[index] == null) {    
  206.                 fastRemove(index);    
  207. returntrue;    
  208.             }    
  209.         } else {    
  210. // 便利ArrayList,找到“元素o”,则删除,并返回true。  
  211. for (int index = 0; index < size; index++)    
  212. if (o.equals(elementData[index])) {    
  213.                 fastRemove(index);    
  214. returntrue;    
  215.             }    
  216.         }    
  217. returnfalse;    
  218.     }    

  219. // 清空ArrayList,将全部的元素设为null  
  220. publicvoid clear() {    
  221.         modCount++;    

  222. for (int i = 0; i < size; i++)    
  223.             elementData[i] = null;    

  224.         size = 0;    
  225.     }    

  226. // 将集合c追加到ArrayList中  
  227. publicboolean addAll(Collectionextends E> c) {    
  228.         Object[] a = c.toArray();    
  229. int numNew = a.length;    
  230.         ensureCapacity(size + numNew);  // Increments modCount  
  231.         System.arraycopy(a, 0, elementData, size, numNew);    
  232.         size += numNew;    
  233. return numNew != 0;    
  234.     }    

  235. // 从index位置开始,将集合c添加到ArrayList  
  236. publicboolean addAll(int index, Collectionextends E> c) {    
  237. if (index > size || index < 0)    
  238. thrownew IndexOutOfBoundsException(    
  239. "Index: " + index + ", Size: " + size);    

  240.         Object[] a = c.toArray();    
  241. int numNew = a.length;    
  242.         ensureCapacity(size + numNew);  // Increments modCount  

  243. int numMoved = size - index;    
  244. if (numMoved > 0)    
  245.             System.arraycopy(elementData, index, elementData, index + numNew,    
  246.                  numMoved);    

  247.         System.arraycopy(a, 0, elementData, index, numNew);    
  248.         size += numNew;    
  249. return numNew != 0;    
  250.     }    

  251. // 删除fromIndex到toIndex之间的全部元素。  
  252. protectedvoid removeRange(int fromIndex, int toIndex) {    
  253.     modCount++;    
  254. int numMoved = size - toIndex;    
  255.         System.arraycopy(elementData, toIndex, elementData, fromIndex,    
  256.                          numMoved);    

  257. // Let gc do its work  
  258. int newSize = size - (toIndex-fromIndex);    
  259. while (size != newSize)    
  260.         elementData[--size] = null;    
  261.     }    

  262. privatevoid RangeCheck(int index) {    
  263. if (index >= size)    
  264. thrownew IndexOutOfBoundsException(    
  265. "Index: "+index+", Size: "+size);    
  266.     }    


  267. // 克隆函数  
  268. public Object clone() {    
  269. try {    
  270.             ArrayList v = (ArrayList) super.clone();    
  271. // 将当前ArrayList的全部元素拷贝到v中  
  272.             v.elementData = Arrays.copyOf(elementData, size);    
  273.             v.modCount = 0;    
  274. return v;    
  275.         } catch (CloneNotSupportedException e) {    
  276. // this shouldn't happen, since we are Cloneable  
  277. thrownew InternalError();    
  278.         }    
  279.     }    


  280. // java.io.Serializable的写入函数  
  281. // 将ArrayList的“容量,所有的元素值”都写入到输出流中  
  282. privatevoid writeObject(java.io.ObjectOutputStream s)    
  283. throws java.io.IOException{    
  284. // Write out element count, and any hidden stuff  
  285. int expectedModCount = modCount;    
  286.     s.defaultWriteObject();    

  287. // 写入“数组的容量”  
  288.         s.writeInt(elementData.length);    

  289. // 写入“数组的每一个元素”  
  290. for (int i=0; i
  291.             s.writeObject(elementData[i]);    

  292. if (modCount != expectedModCount) {    
  293. thrownew ConcurrentModificationException();    
  294.         }    

  295.     }    


  296. // java.io.Serializable的读取函数:根据写入方式读出  
  297. // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出  
  298. privatevoid readObject(java.io.ObjectInputStream s)    
  299. throws java.io.IOException, ClassNotFoundException {    
  300. // Read in size, and any hidden stuff  
  301.         s.defaultReadObject();    

  302. // 从输入流中读取ArrayList的“容量”  
  303. int arrayLength = s.readInt();    
  304.         Object[] a = elementData = new Object[arrayLength];    

  305. // 从输入流中将“所有的元素值”读出  
  306. for (int i=0; i
  307.             a[i] = s.readObject();    
  308.     }    
  309. }  
几点总结

    关于ArrayList的源码,给出几点比较重要的总结:

    1、注意其三个不同的构造方法。无参构造方法构造的ArrayList的容量默认为10,带有Collection参数的构造方法,将Collection转化为数组赋给ArrayList的实现数组elementData。

    2、注意扩充容量的方法ensureCapacity。ArrayList在每次增加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就设置新的容量为旧的容量的1.5倍加1,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),而后用Arrays.copyof()方法将元素拷贝到新的数组(详见下面的第3点)。从中可以看出,当容量不够时,每次增加元素,都要将原来的元素拷贝到一个新的数组中,非常之耗时,也因此建议在事先能确定元素数量的情况下,才使用ArrayList,否则建议使用LinkedList。

    3、ArrayList的实现中大量地调用了Arrays.copyof()和System.arraycopy()方法。我们有必要对这两个方法的实现做下深入的了解。

    首先来看Arrays.copyof()方法。它有很多个重载的方法,但实现思路都是一样的,我们来看泛型版本的源码:

[java]view plaincopy派生到我的代码片
  1. publicstatic  T[] copyOf(T[] original, int newLength) {  
  2. return (T[]) copyOf(original, newLength, original.getClass());  
  3. }  

    很明显调用了另一个copyof方法,该方法有三个参数,最后一个参数指明要转换的数据的类型,其源码如下:

[java]view plaincopy派生到我的代码片
  1. publicstatic  T[] copyOf(U[] original, int newLength, Classextends T[]> newType) {  
  2.     T[] copy = ((Object)newType == (Object)Object[].class)  
  3.         ? (T[]) new Object[newLength]  
  4.         : (T[]) Array.newInstance(newType.getComponentType(), newLength);  
  5.     System.arraycopy(original, 0, copy, 0,  
  6.                      Math.min(original.length, newLength));  
  7. return copy;  
  8. }  

这里可以很明显地看出,该方法实际上是在其内部又创建了一个长度为newlength的数组,调用System.arraycopy()方法,将原来数组中的元素复制到了新的数组中。

    下面来看System.arraycopy()方法。该方法被标记了native,调用了系统的C/C++代码,在JDK中是看不到的,但在openJDK中可以看到其源码。该函数实际上最终调用了C语言的memmove()函数,因此它可以保证同一个数组内元素的正确复制和移动,比一般的复制方法的实现效率要高很多,很适合用来批量处理数组。Java强烈推荐在复制大量数组元素时用该方法,以取得更高的效率。

    4、注意ArrayList的两个转化为静态数组的toArray方法。

    第一个,Object[] toArray()方法。该方法有可能会抛出java.lang.ClassCastException异常,如果直接用向下转型的方法,将整个ArrayList集合转变为指定类型的Array数组,便会抛出该异常,而如果转化为Array数组时不向下转型,而是将每个元素向下转型,则不会抛出该异常,显然对数组中的元素一个个进行向下转型,效率不高,且不太方便。

    第二个, T[] toArray(T[] a)方法。该方法可以直接将ArrayList转换得到的Array进行整体向下转型(转型其实是在该方法的源码中实现的),且从该方法的源码中可以看出,参数a的大小不足时,内部会调用Arrays.copyOf方法,该方法内部创建一个新的数组返回,因此对该方法的常用形式如下:

[java]view plaincopy派生到我的代码片
  1. publicstatic Integer[] vectorToArray2(ArrayList v) {    
  2.     Integer[] newText = (Integer[])v.toArray(new Integer[0]);    
  3. return newText;    
  4. }    

    5、ArrayList基于数组实现,可以通过下标索引直接查找到指定位置的元素,因此查找效率高,但每次插入或删除元素,就要大量地移动元素,插入删除元素的效率低。

    6、在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种情况处理,ArrayList中允许元素为null。


0 0
原创粉丝点击