上一章学习了Collection的架构,并阅读了部分源码,这一章开始,我们将对Collection的具体实现进行详细学习。首先学习List。而ArrayList又是List中最为常用的,因此本章先学习ArrayList。先对ArrayList有个整体的认识,然后学习它的源码,深入剖析ArrayList。

1. ArrayList简介

首先看看ArrayList与Collection的关系:

ArrayList的继承关系如下:

[java] view plaincopyprint?
  1. java.lang.Object
  2. ↳     java.util.AbstractCollection<E>
  3. ↳     java.util.AbstractList<E>
  4. ↳     java.util.ArrayList<E>
  5. public class ArrayList<E> extends AbstractList<E>
  6. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
java.lang.Object↳     java.util.AbstractCollection<E>↳     java.util.AbstractList<E>↳     java.util.ArrayList<E>public class ArrayList<E> extends AbstractList<E>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 plaincopyprint?
  1. /****************** ArrayList中的构造函数 ***************/
  2. // 默认构造函数
  3. ArrayList()
  4. // capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。
  5. ArrayList(int capacity)
  6. // 创建一个包含collection的ArrayList
  7. ArrayList(Collection<? extends E> collection)
  8. /****************** ArrayList中的API ********************/
  9. // Collection中定义的API
  10. boolean             add(E object)
  11. boolean             addAll(Collection<? extends E> collection)
  12. void                clear()
  13. boolean             contains(Object object)
  14. boolean             containsAll(Collection<?> collection)
  15. boolean             equals(Object object)
  16. int                 hashCode()
  17. boolean             isEmpty()
  18. Iterator<E>         iterator()
  19. boolean             remove(Object object)
  20. boolean             removeAll(Collection<?> collection)
  21. boolean             retainAll(Collection<?> collection)
  22. int                 size()
  23. <T> T[]             toArray(T[] array)
  24. Object[]            toArray()
  25. // AbstractCollection中定义的API
  26. void                add(int location, E object)
  27. boolean             addAll(int location, Collection<? extends E> collection)
  28. E                   get(int location)
  29. int                 indexOf(Object object)
  30. int                 lastIndexOf(Object object)
  31. ListIterator<E>     listIterator(int location)
  32. ListIterator<E>     listIterator()
  33. E                   remove(int location)
  34. E                   set(int location, E object)
  35. List<E>             subList(int start, int end)
  36. // ArrayList新增的API
  37. Object               clone()
  38. void                 ensureCapacity(int minimumCapacity)
  39. void                 trimToSize()
  40. void                 removeRange(int fromIndex, int toIndex)
/****************** ArrayList中的构造函数 ***************/
// 默认构造函数
ArrayList()// capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。
ArrayList(int capacity)// 创建一个包含collection的ArrayList
ArrayList(Collection<? extends E> collection)/****************** ArrayList中的API ********************/
// Collection中定义的API
boolean             add(E object)
boolean             addAll(Collection<? extends E> collection)
void                clear()
boolean             contains(Object object)
boolean             containsAll(Collection<?> collection)
boolean             equals(Object object)
int                 hashCode()
boolean             isEmpty()
Iterator<E>         iterator()
boolean             remove(Object object)
boolean             removeAll(Collection<?> collection)
boolean             retainAll(Collection<?> collection)
int                 size()
<T> T[]             toArray(T[] array)
Object[]            toArray()
// AbstractCollection中定义的API
void                add(int location, E object)
boolean             addAll(int location, Collection<? extends E> collection)
E                   get(int location)
int                 indexOf(Object object)
int                 lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
ListIterator<E>     listIterator()
E                   remove(int location)
E                   set(int location, E object)
List<E>             subList(int start, int end)
// ArrayList新增的API
Object               clone()
void                 ensureCapacity(int minimumCapacity)
void                 trimToSize()
void                 removeRange(int fromIndex, int toIndex)

ArrayList包含了两个重要的对象:elementData和size。

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

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

2. ArrayList源码分析(基于JDK1.7)

下面通过分析ArrayList的源码更加深入的了解ArrayList原理。由于ArrayList是通过数组实现的,所以源码比较容易理解:

[java] view plaincopyprint?
  1. package java.util;
  2. public class ArrayList<E> extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  4. {
  5. //序列版本号
  6. private static final long serialVersionUID = 8683452581122892189L;
  7. //默认初始化容量
  8. private static final int DEFAULT_CAPACITY = 10;
  9. //空数组,用来实例化不带容量大小的构造函数
  10. private static final Object[] EMPTY_ELEMENTDATA = {};
  11. //保存ArrayList中数据的数组
  12. private transient Object[] elementData;
  13. //ArrayList中实际数据的数量
  14. private int size;
  15. /******************************** Constructor ***********************************/
  16. //ArrayList带容量大小的构造函数
  17. public ArrayList(int initialCapacity) {
  18. super();
  19. if (initialCapacity < 0)
  20. throw new IllegalArgumentException(“Illegal Capacity: ”+
  21. initialCapacity);
  22. this.elementData = new Object[initialCapacity]; //新建一个数组初始化elementData
  23. }
  24. //不带参数的构造函数
  25. public ArrayList() {
  26. super();
  27. this.elementData = EMPTY_ELEMENTDATA;//使用空数组初始化elementData
  28. }
  29. //用Collection来初始化ArrayList
  30. public ArrayList(Collection<? extends E> c) {
  31. elementData = c.toArray(); //将Collection中的内容转换成数组初始化elementData
  32. size = elementData.length;
  33. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  34. if (elementData.getClass() != Object[].class)
  35. elementData = Arrays.copyOf(elementData, size, Object[].class);
  36. }
  37. /********************************* Array size ************************************/
  38. //重新“修剪”数组容量大小
  39. public void trimToSize() {
  40. modCount++;
  41. //当ArrayList中的元素个数小于elementData数组大小时,重新修整elementData到size大小
  42. if (size < elementData.length) {
  43. elementData = Arrays.copyOf(elementData, size);
  44. }
  45. }
  46. //给数组扩容,该方法是提供给外界调用的,是public的,真正扩容是在下面的private方法里
  47. public void ensureCapacity(int minCapacity) {
  48. int minExpand = (elementData != EMPTY_ELEMENTDATA)
  49. // any size if real element table
  50. ? 0
  51. // larger than default for empty table. It’s already supposed to be
  52. // at default size.
  53. : DEFAULT_CAPACITY;
  54. if (minCapacity > minExpand) {
  55. ensureExplicitCapacity(minCapacity);
  56. }
  57. }
  58. private void ensureCapacityInternal(int minCapacity) {
  59. //如果是个空数组
  60. if (elementData == EMPTY_ELEMENTDATA) {
  61. //取minCapacity和10的较大者
  62. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  63. }
  64. //如果数组已经有数据了
  65. ensureExplicitCapacity(minCapacity);
  66. }
  67. //确保数组容量大于ArrayList中元素个数
  68. private void ensureExplicitCapacity(int minCapacity) {
  69. modCount++; //将“修改统计数”+1
  70. //如果实际数据容量大于数组容量,就给数组扩容
  71. if (minCapacity - elementData.length > 0)
  72. grow(minCapacity);
  73. }
  74. //分配的最大数组空间
  75. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  76. //增大数组空间
  77. private void grow(int minCapacity) {
  78. // overflow-conscious code
  79. int oldCapacity = elementData.length;
  80. int newCapacity = oldCapacity + (oldCapacity >> 1); //在原来容量的基础上加上 oldCapacity/2
  81. if (newCapacity - minCapacity < 0)
  82. newCapacity = minCapacity; //最少保证容量和minCapacity一样
  83. if (newCapacity - MAX_ARRAY_SIZE > 0)
  84. newCapacity = hugeCapacity(minCapacity); //最多不能超过最大容量
  85. // minCapacity is usually close to size, so this is a win:
  86. elementData = Arrays.copyOf(elementData, newCapacity);
  87. }
  88. private static int hugeCapacity(int minCapacity) {
  89. if (minCapacity < 0) // overflow
  90. throw new OutOfMemoryError();
  91. return (minCapacity > MAX_ARRAY_SIZE) ?
  92. Integer.MAX_VALUE :
  93. MAX_ARRAY_SIZE;
  94. }
  95. //返回ArrayList的实际大小
  96. public int size() {
  97. return size;
  98. }
  99. //判断ArrayList是否为空
  100. public boolean isEmpty() {
  101. return size == 0;
  102. }
  103. /****************************** Search Operations *************************/
  104. //判断ArrayList是否包含Object o
  105. public boolean contains(Object o) {
  106. return indexOf(o) >= 0;
  107. }
  108. //正向查找,返回元素的索引值
  109. public int indexOf(Object o) {
  110. if (o == null) {
  111. for (int i = 0; i < size; i++)
  112. if (elementData[i]==null)
  113. return i;
  114. } else {
  115. for (int i = 0; i < size; i++)
  116. if (o.equals(elementData[i]))
  117. return i;
  118. }
  119. return -1;
  120. }
  121. //反向查找,返回元素的索引值
  122. public int lastIndexOf(Object o) {
  123. if (o == null) {
  124. for (int i = size-1; i >= 0; i–)
  125. if (elementData[i]==null)
  126. return i;
  127. } else {
  128. for (int i = size-1; i >= 0; i–)
  129. if (o.equals(elementData[i]))
  130. return i;
  131. }
  132. return -1;
  133. }
  134. /******************************* Clone *********************************/
  135. //克隆函数
  136. public Object clone() {
  137. try {
  138. @SuppressWarnings(“unchecked”)
  139. ArrayList<E> v = (ArrayList<E>) super.clone();
  140. //将当前ArrayList的全部元素拷贝到v中
  141. v.elementData = Arrays.copyOf(elementData, size);
  142. v.modCount = 0;
  143. return v;
  144. } catch (CloneNotSupportedException e) {
  145. // this shouldn’t happen, since we are Cloneable
  146. throw new InternalError();
  147. }
  148. }
  149. /********************************* toArray *****************************/
  150. /**
  151. * 返回一个Object数组,包含ArrayList中所有的元素
  152. * toArray()方法扮演着array-based和collection-based API之间的桥梁
  153. */
  154. public Object[] toArray() {
  155. return Arrays.copyOf(elementData, size);
  156. }
  157. //返回ArrayList的模板数组
  158. @SuppressWarnings(“unchecked”)
  159. public <T> T[] toArray(T[] a) {
  160. //如果数组a的大小 < ArrayList的元素个数,
  161. //则新建一个T[]数组,大小为ArrayList元素个数,并将“ArrayList”全部拷贝到新数组中。
  162. if (a.length < size)
  163. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  164. //如果数组a的大小 >= ArrayList的元素个数,
  165. //则将ArrayList全部拷贝到新数组a中。
  166. System.arraycopy(elementData, 0, a, 0, size);
  167. if (a.length > size)
  168. a[size] = null;
  169. return a;
  170. }
  171. /******************** Positional Access Operations ********************/
  172. @SuppressWarnings(“unchecked”)
  173. E elementData(int index) {
  174. return (E) elementData[index];
  175. }
  176. //获取index位置的元素值
  177. public E get(int index) {
  178. rangeCheck(index); //首先判断index的范围是否合法
  179. return elementData(index);
  180. }
  181. //将index位置的值设为element,并返回原来的值
  182. public E set(int index, E element) {
  183. rangeCheck(index);
  184. E oldValue = elementData(index);
  185. elementData[index] = element;
  186. return oldValue;
  187. }
  188. //将e添加到ArrayList中
  189. public boolean add(E e) {
  190. ensureCapacityInternal(size + 1);  // Increments modCount!!
  191. elementData[size++] = e;
  192. return true;
  193. }
  194. //将element添加到ArrayList的指定位置
  195. public void add(int index, E element) {
  196. rangeCheckForAdd(index);
  197. ensureCapacityInternal(size + 1);  // Increments modCount!!
  198. //将index以及index之后的数据复制到index+1的位置往后,即从index开始向后挪了一位
  199. System.arraycopy(elementData, index, elementData, index + 1,
  200. size - index);
  201. elementData[index] = element; //然后在index处插入element
  202. size++;
  203. }
  204. //删除ArrayList指定位置的元素
  205. public E remove(int index) {
  206. rangeCheck(index);
  207. modCount++;
  208. E oldValue = elementData(index);
  209. int numMoved = size - index - 1;
  210. if (numMoved > 0)
  211. //向左挪一位,index位置原来的数据已经被覆盖了
  212. System.arraycopy(elementData, index+1, elementData, index,
  213. numMoved);
  214. //多出来的最后一位删掉
  215. elementData[–size] = null; // clear to let GC do its work
  216. return oldValue;
  217. }
  218. //删除ArrayList中指定的元素
  219. public boolean remove(Object o) {
  220. if (o == null) {
  221. for (int index = 0; index < size; index++)
  222. if (elementData[index] == null) {
  223. fastRemove(index);
  224. return true;
  225. }
  226. } else {
  227. for (int index = 0; index < size; index++)
  228. if (o.equals(elementData[index])) {
  229. fastRemove(index);
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. //private的快速删除与上面的public普通删除区别在于,没有进行边界判断以及不返回删除值
  236. private void fastRemove(int index) {
  237. modCount++;
  238. int numMoved = size - index - 1;
  239. if (numMoved > 0)
  240. System.arraycopy(elementData, index+1, elementData, index,
  241. numMoved);
  242. elementData[–size] = null; // clear to let GC do its work
  243. }
  244. //清空ArrayList,将全部元素置为null
  245. public void clear() {
  246. modCount++;
  247. // clear to let GC do its work
  248. for (int i = 0; i < size; i++)
  249. elementData[i] = null;
  250. size = 0;
  251. }
  252. //将集合C中所有的元素添加到ArrayList中
  253. public boolean addAll(Collection<? extends E> c) {
  254. Object[] a = c.toArray();
  255. int numNew = a.length;
  256. ensureCapacityInternal(size + numNew);  // Increments modCount
  257. //在原来数组的后面添加c中所有的元素
  258. System.arraycopy(a, 0, elementData, size, numNew);
  259. size += numNew;
  260. return numNew != 0;
  261. }
  262. //从index位置开始,将集合C中所欲的元素添加到ArrayList中
  263. public boolean addAll(int index, Collection<? extends E> c) {
  264. rangeCheckForAdd(index);
  265. Object[] a = c.toArray();
  266. int numNew = a.length;
  267. ensureCapacityInternal(size + numNew);  // Increments modCount
  268. int numMoved = size - index;
  269. if (numMoved > 0)
  270. //将index开始向后的所有数据,向后移动numNew个位置,给新插入的数据腾出空间
  271. System.arraycopy(elementData, index, elementData, index + numNew,
  272. numMoved);
  273. //将集合C中的数据插到刚刚腾出的位置
  274. System.arraycopy(a, 0, elementData, index, numNew);
  275. size += numNew;
  276. return numNew != 0;
  277. }
  278. //删除从fromIndex到toIndex之间的数据,不包括toIndex位置的数据
  279. protected void removeRange(int fromIndex, int toIndex) {
  280. modCount++;
  281. int numMoved = size - toIndex;
  282. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  283. numMoved);
  284. // clear to let GC do its work
  285. int newSize = size - (toIndex-fromIndex);
  286. for (int i = newSize; i < size; i++) {
  287. elementData[i] = null;
  288. }
  289. size = newSize;
  290. }
  291. //范围检测
  292. private void rangeCheck(int index) {
  293. if (index >= size)
  294. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  295. }
  296. //add和addAll方法中的范围检测
  297. private void rangeCheckForAdd(int index) {
  298. if (index > size || index < 0)
  299. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  300. }
  301. private String outOfBoundsMsg(int index) {
  302. return “Index: ”+index+“, Size: ”+size;
  303. }
  304. //删除ArrayList中所有集合C中包含的数据
  305. public boolean removeAll(Collection<?> c) {
  306. return batchRemove(c, false);
  307. }
  308. //删除ArrayList中除了集合C中包含的数据外的其他所有数据
  309. public boolean retainAll(Collection<?> c) {
  310. return batchRemove(c, true);
  311. }
  312. //批量删除
  313. private boolean batchRemove(Collection<?> c, boolean complement) {
  314. final Object[] elementData = this.elementData;
  315. int r = 0, w = 0;
  316. boolean modified = false;
  317. try {
  318. for (; r < size; r++)
  319. if (c.contains(elementData[r]) == complement)
  320. elementData[w++] = elementData[r];
  321. } finally {
  322. // Preserve behavioral compatibility with AbstractCollection,
  323. // even if c.contains() throws.
  324. //官方的注释是为了保持和AbstractCollection的兼容性
  325. //我的理解是上面c.contains抛出了异常,导致for循环终止,那么必然会导致r != size
  326. //所以0-w之间是需要保留的数据,同时从w索引开始将剩下没有循环的数据(也就是从r开始的)拷贝回来,也保留
  327. if (r != size) {
  328. System.arraycopy(elementData, r,
  329. elementData, w,
  330. size - r);
  331. w += size - r;
  332. }
  333. //for循环完毕,检测了所有的元素
  334. //0-w之间保存了需要留下的数据,w开始以及后面的数据全部清空
  335. if (w != size) {
  336. // clear to let GC do its work
  337. for (int i = w; i < size; i++)
  338. elementData[i] = null;
  339. modCount += size - w;
  340. size = w;
  341. modified = true;
  342. }
  343. }
  344. return modified;
  345. }
  346. /***************************** Writer and Read Object *************************/
  347. //java.io.Serializable的写入函数
  348. //将ArrayList的“容量、所有的元素值”都写入到输出流中
  349. private void writeObject(java.io.ObjectOutputStream s)
  350. throws java.io.IOException{
  351. // Write out element count, and any hidden stuff
  352. int expectedModCount = modCount;
  353. s.defaultWriteObject();
  354. // Write out size as capacity for behavioural compatibility with clone()
  355. //写入“数组的容量”,保持与clone()的兼容性
  356. s.writeInt(size);
  357. //写入“数组的每一个元素”
  358. for (int i=0; i<size; i++) {
  359. s.writeObject(elementData[i]);
  360. }
  361. if (modCount != expectedModCount) {
  362. throw new ConcurrentModificationException();
  363. }
  364. }
  365. //java.io.Serializable的读取函数:根据写入方式读出
  366. private void readObject(java.io.ObjectInputStream s)
  367. throws java.io.IOException, ClassNotFoundException {
  368. elementData = EMPTY_ELEMENTDATA;
  369. // Read in size, and any hidden stuff
  370. s.defaultReadObject();
  371. //从输入流中读取ArrayList的“容量”
  372. s.readInt(); // ignored
  373. if (size > 0) {
  374. // be like clone(), allocate array based upon size not capacity
  375. ensureCapacityInternal(size);
  376. Object[] a = elementData;
  377. //从输入流中将“所有元素值”读出
  378. for (int i=0; i<size; i++) {
  379. a[i] = s.readObject();
  380. }
  381. }
  382. }
  383. /******************************** Iterators ************************************/
  384. /**
  385. * 该部分的方法重写了AbstractList抽象类中Iterator部分的方法,因为ArrayList继承
  386. * 了AbstractList,基本大同小异,只是这里针对本类的数组,思想与AbstractList一致
  387. * 可以参照上一章Collection架构与源码分析的AbatractList部分
  388. */
  389. public ListIterator<E> listIterator(int index) {
  390. if (index < 0 || index > size)
  391. throw new IndexOutOfBoundsException(“Index: ”+index);
  392. return new ListItr(index);
  393. }
  394. public ListIterator<E> listIterator() {
  395. return new ListItr(0);
  396. }
  397. public Iterator<E> iterator() {
  398. return new Itr();
  399. }
  400. private class Itr implements Iterator<E> {
  401. int cursor;       // index of next element to return
  402. int lastRet = -1; // index of last element returned; -1 if no such
  403. int expectedModCount = modCount;
  404. public boolean hasNext() {
  405. return cursor != size;
  406. }
  407. @SuppressWarnings(“unchecked”)
  408. public E next() {
  409. checkForComodification();
  410. int i = cursor;
  411. if (i >= size)
  412. throw new NoSuchElementException();
  413. Object[] elementData = ArrayList.this.elementData;
  414. if (i >= elementData.length)
  415. throw new ConcurrentModificationException();
  416. cursor = i + 1;
  417. return (E) elementData[lastRet = i];
  418. }
  419. public void remove() {
  420. if (lastRet < 0)
  421. throw new IllegalStateException();
  422. checkForComodification();
  423. try {
  424. ArrayList.this.remove(lastRet);
  425. cursor = lastRet;
  426. lastRet = -1;
  427. expectedModCount = modCount;
  428. } catch (IndexOutOfBoundsException ex) {
  429. throw new ConcurrentModificationException();
  430. }
  431. }
  432. final void checkForComodification() {
  433. if (modCount != expectedModCount)
  434. throw new ConcurrentModificationException();
  435. }
  436. }
  437. private class ListItr extends Itr implements ListIterator<E> {
  438. ListItr(int index) {
  439. super();
  440. cursor = index;
  441. }
  442. public boolean hasPrevious() {
  443. return cursor != 0;
  444. }
  445. public int nextIndex() {
  446. return cursor;
  447. }
  448. public int previousIndex() {
  449. return cursor - 1;
  450. }
  451. @SuppressWarnings(“unchecked”)
  452. public E previous() {
  453. checkForComodification();
  454. int i = cursor - 1;
  455. if (i < 0)
  456. throw new NoSuchElementException();
  457. Object[] elementData = ArrayList.this.elementData;
  458. if (i >= elementData.length)
  459. throw new ConcurrentModificationException();
  460. cursor = i;
  461. return (E) elementData[lastRet = i];
  462. }
  463. public void set(E e) {
  464. if (lastRet < 0)
  465. throw new IllegalStateException();
  466. checkForComodification();
  467. try {
  468. ArrayList.this.set(lastRet, e);
  469. } catch (IndexOutOfBoundsException ex) {
  470. throw new ConcurrentModificationException();
  471. }
  472. }
  473. public void add(E e) {
  474. checkForComodification();
  475. try {
  476. int i = cursor;
  477. ArrayList.this.add(i, e);
  478. cursor = i + 1;
  479. lastRet = -1;
  480. expectedModCount = modCount;
  481. } catch (IndexOutOfBoundsException ex) {
  482. throw new ConcurrentModificationException();
  483. }
  484. }
  485. }
  486. public List<E> subList(int fromIndex, int toIndex) {
  487. subListRangeCheck(fromIndex, toIndex, size);
  488. return new SubList(this, 0, fromIndex, toIndex);
  489. }
  490. static void subListRangeCheck(int fromIndex, int toIndex, int size) {
  491. if (fromIndex < 0)
  492. throw new IndexOutOfBoundsException(“fromIndex = ” + fromIndex);
  493. if (toIndex > size)
  494. throw new IndexOutOfBoundsException(“toIndex = ” + toIndex);
  495. if (fromIndex > toIndex)
  496. throw new IllegalArgumentException(“fromIndex(“ + fromIndex +
  497. ”) > toIndex(“ + toIndex + “)”);
  498. }
  499. private class SubList extends AbstractList<E> implements RandomAccess {
  500. private final AbstractList<E> parent;
  501. private final int parentOffset;
  502. private final int offset;
  503. int size;
  504. SubList(AbstractList<E> parent,
  505. int offset, int fromIndex, int toIndex) {
  506. this.parent = parent;
  507. this.parentOffset = fromIndex;
  508. this.offset = offset + fromIndex;
  509. this.size = toIndex - fromIndex;
  510. this.modCount = ArrayList.this.modCount;
  511. }
  512. public E set(int index, E e) {
  513. rangeCheck(index);
  514. checkForComodification();
  515. E oldValue = ArrayList.this.elementData(offset + index);
  516. ArrayList.this.elementData[offset + index] = e;
  517. return oldValue;
  518. }
  519. public E get(int index) {
  520. rangeCheck(index);
  521. checkForComodification();
  522. return ArrayList.this.elementData(offset + index);
  523. }
  524. public int size() {
  525. checkForComodification();
  526. return this.size;
  527. }
  528. public void add(int index, E e) {
  529. rangeCheckForAdd(index);
  530. checkForComodification();
  531. parent.add(parentOffset + index, e);
  532. this.modCount = parent.modCount;
  533. this.size++;
  534. }
  535. public E remove(int index) {
  536. rangeCheck(index);
  537. checkForComodification();
  538. E result = parent.remove(parentOffset + index);
  539. this.modCount = parent.modCount;
  540. this.size–;
  541. return result;
  542. }
  543. protected void removeRange(int fromIndex, int toIndex) {
  544. checkForComodification();
  545. parent.removeRange(parentOffset + fromIndex,
  546. parentOffset + toIndex);
  547. this.modCount = parent.modCount;
  548. this.size -= toIndex - fromIndex;
  549. }
  550. public boolean addAll(Collection<? extends E> c) {
  551. return addAll(this.size, c);
  552. }
  553. public boolean addAll(int index, Collection<? extends E> c) {
  554. rangeCheckForAdd(index);
  555. int cSize = c.size();
  556. if (cSize==0)
  557. return false;
  558. checkForComodification();
  559. parent.addAll(parentOffset + index, c);
  560. this.modCount = parent.modCount;
  561. this.size += cSize;
  562. return true;
  563. }
  564. public Iterator<E> iterator() {
  565. return listIterator();
  566. }
  567. public ListIterator<E> listIterator(final int index) {
  568. checkForComodification();
  569. rangeCheckForAdd(index);
  570. final int offset = this.offset;
  571. return new ListIterator<E>() {
  572. int cursor = index;
  573. int lastRet = -1;
  574. int expectedModCount = ArrayList.this.modCount;
  575. public boolean hasNext() {
  576. return cursor != SubList.this.size;
  577. }
  578. @SuppressWarnings(“unchecked”)
  579. public E next() {
  580. checkForComodification();
  581. int i = cursor;
  582. if (i >= SubList.this.size)
  583. throw new NoSuchElementException();
  584. Object[] elementData = ArrayList.this.elementData;
  585. if (offset + i >= elementData.length)
  586. throw new ConcurrentModificationException();
  587. cursor = i + 1;
  588. return (E) elementData[offset + (lastRet = i)];
  589. }
  590. public boolean hasPrevious() {
  591. return cursor != 0;
  592. }
  593. @SuppressWarnings(“unchecked”)
  594. public E previous() {
  595. checkForComodification();
  596. int i = cursor - 1;
  597. if (i < 0)
  598. throw new NoSuchElementException();
  599. Object[] elementData = ArrayList.this.elementData;
  600. if (offset + i >= elementData.length)
  601. throw new ConcurrentModificationException();
  602. cursor = i;
  603. return (E) elementData[offset + (lastRet = i)];
  604. }
  605. public int nextIndex() {
  606. return cursor;
  607. }
  608. public int previousIndex() {
  609. return cursor - 1;
  610. }
  611. public void remove() {
  612. if (lastRet < 0)
  613. throw new IllegalStateException();
  614. checkForComodification();
  615. try {
  616. SubList.this.remove(lastRet);
  617. cursor = lastRet;
  618. lastRet = -1;
  619. expectedModCount = ArrayList.this.modCount;
  620. } catch (IndexOutOfBoundsException ex) {
  621. throw new ConcurrentModificationException();
  622. }
  623. }
  624. public void set(E e) {
  625. if (lastRet < 0)
  626. throw new IllegalStateException();
  627. checkForComodification();
  628. try {
  629. ArrayList.this.set(offset + lastRet, e);
  630. } catch (IndexOutOfBoundsException ex) {
  631. throw new ConcurrentModificationException();
  632. }
  633. }
  634. public void add(E e) {
  635. checkForComodification();
  636. try {
  637. int i = cursor;
  638. SubList.this.add(i, e);
  639. cursor = i + 1;
  640. lastRet = -1;
  641. expectedModCount = ArrayList.this.modCount;
  642. } catch (IndexOutOfBoundsException ex) {
  643. throw new ConcurrentModificationException();
  644. }
  645. }
  646. final void checkForComodification() {
  647. if (expectedModCount != ArrayList.this.modCount)
  648. throw new ConcurrentModificationException();
  649. }
  650. };
  651. }
  652. public List<E> subList(int fromIndex, int toIndex) {
  653. subListRangeCheck(fromIndex, toIndex, size);
  654. return new SubList(this, offset, fromIndex, toIndex);
  655. }
  656. private void rangeCheck(int index) {
  657. if (index < 0 || index >= this.size)
  658. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  659. }
  660. private void rangeCheckForAdd(int index) {
  661. if (index < 0 || index > this.size)
  662. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  663. }
  664. private String outOfBoundsMsg(int index) {
  665. return “Index: ”+index+“, Size: ”+this.size;
  666. }
  667. private void checkForComodification() {
  668. if (ArrayList.this.modCount != this.modCount)
  669. throw new ConcurrentModificationException();
  670. }
  671. }
  672. }
package java.util;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 = {};//保存ArrayList中数据的数组private transient Object[] elementData;//ArrayList中实际数据的数量private int size;/******************************** Constructor ***********************************///ArrayList带容量大小的构造函数public ArrayList(int initialCapacity) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity]; //新建一个数组初始化elementData}//不带参数的构造函数public ArrayList() {super();this.elementData = EMPTY_ELEMENTDATA;//使用空数组初始化elementData}//用Collection来初始化ArrayListpublic ArrayList(Collection<? extends E> c) {elementData = c.toArray(); //将Collection中的内容转换成数组初始化elementDatasize = elementData.length;// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, size, Object[].class);}/********************************* Array size ************************************///重新“修剪”数组容量大小public void trimToSize() {modCount++;//当ArrayList中的元素个数小于elementData数组大小时,重新修整elementData到size大小if (size < elementData.length) {elementData = Arrays.copyOf(elementData, size);}}//给数组扩容,该方法是提供给外界调用的,是public的,真正扩容是在下面的private方法里public void ensureCapacity(int minCapacity) {int minExpand = (elementData != EMPTY_ELEMENTDATA)// any size if real element table? 0// larger than default for empty table. It's already supposed to be// at default size.: DEFAULT_CAPACITY;if (minCapacity > minExpand) {ensureExplicitCapacity(minCapacity);}}private void ensureCapacityInternal(int minCapacity) {//如果是个空数组if (elementData == EMPTY_ELEMENTDATA) {//取minCapacity和10的较大者minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}//如果数组已经有数据了ensureExplicitCapacity(minCapacity);}//确保数组容量大于ArrayList中元素个数private void ensureExplicitCapacity(int minCapacity) {modCount++; //将“修改统计数”+1//如果实际数据容量大于数组容量,就给数组扩容if (minCapacity - elementData.length > 0)grow(minCapacity);}//分配的最大数组空间private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//增大数组空间private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1); //在原来容量的基础上加上 oldCapacity/2if (newCapacity - minCapacity < 0)newCapacity = minCapacity; //最少保证容量和minCapacity一样if (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity); //最多不能超过最大容量// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}//返回ArrayList的实际大小public int size() {return size;}//判断ArrayList是否为空public boolean isEmpty() {return size == 0;} /****************************** Search Operations *************************///判断ArrayList是否包含Object opublic boolean contains(Object o) {return indexOf(o) >= 0;}//正向查找,返回元素的索引值public int indexOf(Object o) {if (o == null) {for (int i = 0; i < size; i++)if (elementData[i]==null)return i;} else {for (int i = 0; i < size; i++)if (o.equals(elementData[i]))return i;}return -1;}//反向查找,返回元素的索引值public int lastIndexOf(Object o) {if (o == null) {for (int i = size-1; i >= 0; i--)if (elementData[i]==null)return i;} else {for (int i = size-1; i >= 0; i--)if (o.equals(elementData[i]))return i;}return -1;}/******************************* Clone *********************************///克隆函数public Object clone() {try {@SuppressWarnings("unchecked")ArrayList<E> v = (ArrayList<E>) super.clone();//将当前ArrayList的全部元素拷贝到v中v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError();}}/********************************* toArray *****************************//*** 返回一个Object数组,包含ArrayList中所有的元素* toArray()方法扮演着array-based和collection-based API之间的桥梁*/public Object[] toArray() {return Arrays.copyOf(elementData, size);}//返回ArrayList的模板数组@SuppressWarnings("unchecked")public <T> T[] toArray(T[] a) {//如果数组a的大小 < ArrayList的元素个数,//则新建一个T[]数组,大小为ArrayList元素个数,并将“ArrayList”全部拷贝到新数组中。if (a.length < size)return (T[]) Arrays.copyOf(elementData, size, a.getClass());//如果数组a的大小 >= ArrayList的元素个数,//则将ArrayList全部拷贝到新数组a中。System.arraycopy(elementData, 0, a, 0, size);if (a.length > size)a[size] = null;return a;}/******************** Positional Access Operations ********************/@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}//获取index位置的元素值public E get(int index) {rangeCheck(index); //首先判断index的范围是否合法return elementData(index);}//将index位置的值设为element,并返回原来的值public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}//将e添加到ArrayList中public boolean add(E e) {ensureCapacityInternal(size + 1);  // Increments modCount!!elementData[size++] = e;return true;}//将element添加到ArrayList的指定位置public void add(int index, E element) {rangeCheckForAdd(index);ensureCapacityInternal(size + 1);  // Increments modCount!!//将index以及index之后的数据复制到index+1的位置往后,即从index开始向后挪了一位System.arraycopy(elementData, index, elementData, index + 1,size - index); elementData[index] = element; //然后在index处插入elementsize++;}//删除ArrayList指定位置的元素public E remove(int index) {rangeCheck(index);modCount++;E oldValue = elementData(index);int numMoved = size - index - 1;if (numMoved > 0)//向左挪一位,index位置原来的数据已经被覆盖了System.arraycopy(elementData, index+1, elementData, index,numMoved);//多出来的最后一位删掉elementData[--size] = null; // clear to let GC do its workreturn oldValue;}//删除ArrayList中指定的元素public boolean remove(Object o) {if (o == null) {for (int index = 0; index < size; index++)if (elementData[index] == null) {fastRemove(index);return true;}} else {for (int index = 0; index < size; index++)if (o.equals(elementData[index])) {fastRemove(index);return true;}}return false;}//private的快速删除与上面的public普通删除区别在于,没有进行边界判断以及不返回删除值private void fastRemove(int index) {modCount++;int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null; // clear to let GC do its work}//清空ArrayList,将全部元素置为nullpublic void clear() {modCount++;// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}//将集合C中所有的元素添加到ArrayList中public boolean addAll(Collection<? extends E> c) {Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCount//在原来数组的后面添加c中所有的元素System.arraycopy(a, 0, elementData, size, numNew);size += numNew;return numNew != 0;}//从index位置开始,将集合C中所欲的元素添加到ArrayList中public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountint numMoved = size - index;if (numMoved > 0)//将index开始向后的所有数据,向后移动numNew个位置,给新插入的数据腾出空间System.arraycopy(elementData, index, elementData, index + numNew,numMoved);//将集合C中的数据插到刚刚腾出的位置System.arraycopy(a, 0, elementData, index, numNew);size += numNew;return numNew != 0;}//删除从fromIndex到toIndex之间的数据,不包括toIndex位置的数据protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// clear to let GC do its workint newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}//范围检测private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}//add和addAll方法中的范围检测private void rangeCheckForAdd(int index) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size;}//删除ArrayList中所有集合C中包含的数据public boolean removeAll(Collection<?> c) {return batchRemove(c, false);}//删除ArrayList中除了集合C中包含的数据外的其他所有数据public boolean retainAll(Collection<?> c) {return batchRemove(c, true);}//批量删除private boolean batchRemove(Collection<?> c, boolean complement) {final Object[] elementData = this.elementData;int r = 0, w = 0;boolean modified = false;try {for (; r < size; r++)if (c.contains(elementData[r]) == complement)elementData[w++] = elementData[r];} finally {// Preserve behavioral compatibility with AbstractCollection,// even if c.contains() throws.//官方的注释是为了保持和AbstractCollection的兼容性//我的理解是上面c.contains抛出了异常,导致for循环终止,那么必然会导致r != size//所以0-w之间是需要保留的数据,同时从w索引开始将剩下没有循环的数据(也就是从r开始的)拷贝回来,也保留if (r != size) {System.arraycopy(elementData, r,elementData, w,size - r);w += size - r;}//for循环完毕,检测了所有的元素//0-w之间保存了需要留下的数据,w开始以及后面的数据全部清空if (w != size) {// clear to let GC do its workfor (int i = w; i < size; i++)elementData[i] = null;modCount += size - w;size = w;modified = true;}}return modified;}/***************************** Writer and Read Object *************************///java.io.Serializable的写入函数//将ArrayList的“容量、所有的元素值”都写入到输出流中private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();// Write out size as capacity for behavioural compatibility with clone()//写入“数组的容量”,保持与clone()的兼容性s.writeInt(size);//写入“数组的每一个元素”for (int i=0; i<size; i++) {s.writeObject(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}//java.io.Serializable的读取函数:根据写入方式读出private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;// Read in size, and any hidden stuffs.defaultReadObject();//从输入流中读取ArrayList的“容量”s.readInt(); // ignoredif (size > 0) {// be like clone(), allocate array based upon size not capacityensureCapacityInternal(size);Object[] a = elementData;//从输入流中将“所有元素值”读出for (int i=0; i<size; i++) {a[i] = s.readObject();}}}/******************************** Iterators ************************************//*** 该部分的方法重写了AbstractList抽象类中Iterator部分的方法,因为ArrayList继承* 了AbstractList,基本大同小异,只是这里针对本类的数组,思想与AbstractList一致* 可以参照上一章Collection架构与源码分析的AbatractList部分*/public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}public ListIterator<E> listIterator() {return new ListItr(0);}public Iterator<E> iterator() {return new Itr();}private class Itr implements Iterator<E> {int cursor;       // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount;public boolean hasNext() {return cursor != size;}@SuppressWarnings("unchecked")public E next() {checkForComodification();int i = cursor;if (i >= size)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;return (E) elementData[lastRet = i];}public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}private class ListItr extends Itr implements ListIterator<E> {ListItr(int index) {super();cursor = index;}public boolean hasPrevious() {return cursor != 0;}public int nextIndex() {return cursor;}public int previousIndex() {return cursor - 1;}@SuppressWarnings("unchecked")public E previous() {checkForComodification();int i = cursor - 1;if (i < 0)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i;return (E) elementData[lastRet = i];}public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.set(lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void add(E e) {checkForComodification();try {int i = cursor;ArrayList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}}public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, 0, fromIndex, toIndex);}static void subListRangeCheck(int fromIndex, int toIndex, int size) {if (fromIndex < 0)throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);if (toIndex > size)throw new IndexOutOfBoundsException("toIndex = " + toIndex);if (fromIndex > toIndex)throw new IllegalArgumentException("fromIndex(" + fromIndex +") > toIndex(" + toIndex + ")");}private class SubList extends AbstractList<E> implements RandomAccess {private final AbstractList<E> parent;private final int parentOffset;private final int offset;int size;SubList(AbstractList<E> parent,int offset, int fromIndex, int toIndex) {this.parent = parent;this.parentOffset = fromIndex;this.offset = offset + fromIndex;this.size = toIndex - fromIndex;this.modCount = ArrayList.this.modCount;}public E set(int index, E e) {rangeCheck(index);checkForComodification();E oldValue = ArrayList.this.elementData(offset + index);ArrayList.this.elementData[offset + index] = e;return oldValue;}public E get(int index) {rangeCheck(index);checkForComodification();return ArrayList.this.elementData(offset + index);}public int size() {checkForComodification();return this.size;}public void add(int index, E e) {rangeCheckForAdd(index);checkForComodification();parent.add(parentOffset + index, e);this.modCount = parent.modCount;this.size++;}public E remove(int index) {rangeCheck(index);checkForComodification();E result = parent.remove(parentOffset + index);this.modCount = parent.modCount;this.size--;return result;}protected void removeRange(int fromIndex, int toIndex) {checkForComodification();parent.removeRange(parentOffset + fromIndex,parentOffset + toIndex);this.modCount = parent.modCount;this.size -= toIndex - fromIndex;}public boolean addAll(Collection<? extends E> c) {return addAll(this.size, c);}public boolean addAll(int index, Collection<? extends E> c) {rangeCheckForAdd(index);int cSize = c.size();if (cSize==0)return false;checkForComodification();parent.addAll(parentOffset + index, c);this.modCount = parent.modCount;this.size += cSize;return true;}public Iterator<E> iterator() {return listIterator();}public ListIterator<E> listIterator(final int index) {checkForComodification();rangeCheckForAdd(index);final int offset = this.offset;return new ListIterator<E>() {int cursor = index;int lastRet = -1;int expectedModCount = ArrayList.this.modCount;public boolean hasNext() {return cursor != SubList.this.size;}@SuppressWarnings("unchecked")public E next() {checkForComodification();int i = cursor;if (i >= SubList.this.size)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (offset + i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;return (E) elementData[offset + (lastRet = i)];}public boolean hasPrevious() {return cursor != 0;}@SuppressWarnings("unchecked")public E previous() {checkForComodification();int i = cursor - 1;if (i < 0)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (offset + i >= elementData.length)throw new ConcurrentModificationException();cursor = i;return (E) elementData[offset + (lastRet = i)];}public int nextIndex() {return cursor;}public int previousIndex() {return cursor - 1;}public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {SubList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = ArrayList.this.modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();try {ArrayList.this.set(offset + lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}public void add(E e) {checkForComodification();try {int i = cursor;SubList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = ArrayList.this.modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}}final void checkForComodification() {if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();}};}public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);return new SubList(this, offset, fromIndex, toIndex);}private void rangeCheck(int index) {if (index < 0 || index >= this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private void rangeCheckForAdd(int index) {if (index < 0 || index > this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+this.size;}private void checkForComodification() {if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();}}
}

总结一下:

1). ArrayList实际上是通过一个数组去保存数据的,当我们构造ArrayList时,如果使用默认构造函数,最后ArrayList的默认容量大小是10。

2). 当ArrayList容量不足以容纳全部元素时,ArrayList会自动扩张容量,新的容量 = 原始容量 + 原始容量 / 2。

3). ArrayList的克隆函数,即是将全部元素克隆到一个数组中。

4. ArrayList实现java.io.Serializable的方式。当写入到输出流时,先写入“容量”,再依次写出“每一个元素”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。

3. ArrayList遍历方式

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

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

[java] view plaincopyprint?
  1. Integer value = null;
  2. Iterator it = list.iterator();
  3. while (it.hasNext()) {
  4. value = (Integer)it.next();
  5. }
Integer value = null;
Iterator it = list.iterator();
while (it.hasNext()) {value = (Integer)it.next();
}

2). 随机访问,通过索引值去遍历。由于ArrayList实现了RandomAccess接口,所以它支持通过索引值去随机访问元素。

[java] view plaincopyprint?
  1. Integer value = null;
  2. int size = list.size();
  3. for (int i = 0; i < size; i++) {
  4. value = (Integer)list.get(i);
  5. }
Integer value = null;
int size = list.size();
for (int i = 0; i < size; i++) {value = (Integer)list.get(i);
}

3). 通过for循环遍历。

[java] view plaincopyprint?
  1. Integer value = null;
  2. for (Integer integ : list) {
  3. value = integ;
  4. }
Integer value = null;
for (Integer integ : list) {value = integ;
}

下面写了一个测试用例,比较这三种遍历方式的效率:

[java] view plaincopyprint?
  1. import java.util.*;
  2. /*
  3. * @description ArrayList三种遍历方式效率的测试
  4. * @author eson_15
  5. */
  6. public class ArrayListRandomAccessTest {
  7. public static void main(String[] args) {
  8. List<Integer> list = new ArrayList<Integer>();
  9. for (int i=0; i<500000; i++)
  10. list.add(i);
  11. isRandomAccessSupported(list);//判断是否支持RandomAccess
  12. iteratorThroughRandomAccess(list) ;
  13. iteratorThroughIterator(list) ;
  14. iteratorThroughFor(list) ;
  15. }
  16. private static void isRandomAccessSupported(List<Integer> list) {
  17. if (list instanceof RandomAccess) {
  18. System.out.println(”RandomAccess implemented!”);
  19. } else {
  20. System.out.println(”RandomAccess not implemented!”);
  21. }
  22. }
  23. public static void iteratorThroughRandomAccess(List<Integer> list) {
  24. long startTime;
  25. long endTime;
  26. startTime = System.currentTimeMillis();
  27. for (int i=0; i<list.size(); i++) {
  28. list.get(i);
  29. }
  30. endTime = System.currentTimeMillis();
  31. long interval = endTime - startTime;
  32. System.out.println(”RandomAccess遍历时间:” + interval+“ ms”);
  33. }
  34. public static void iteratorThroughIterator(List<Integer> list) {
  35. long startTime;
  36. long endTime;
  37. startTime = System.currentTimeMillis();
  38. for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {
  39. it.next();
  40. }
  41. endTime = System.currentTimeMillis();
  42. long interval = endTime - startTime;
  43. System.out.println(”Iterator遍历时间:” + interval+“ ms”);
  44. }
  45. @SuppressWarnings(“unused”)
  46. public static void iteratorThroughFor(List<Integer> list) {
  47. long startTime;
  48. long endTime;
  49. startTime = System.currentTimeMillis();
  50. for(Object obj : list)
  51. ;
  52. endTime = System.currentTimeMillis();
  53. long interval = endTime - startTime;
  54. System.out.println(”For循环遍历时间:” + interval+“ ms”);
  55. }
  56. }
import java.util.*;/** @description ArrayList三种遍历方式效率的测试* @author eson_15*/
public class ArrayListRandomAccessTest {public static void main(String[] args) {List<Integer> list = new ArrayList<Integer>();for (int i=0; i<500000; i++)list.add(i);isRandomAccessSupported(list);//判断是否支持RandomAccessiteratorThroughRandomAccess(list) ;iteratorThroughIterator(list) ;iteratorThroughFor(list) ;}private static void isRandomAccessSupported(List<Integer> list) {if (list instanceof RandomAccess) {System.out.println("RandomAccess implemented!");} else {System.out.println("RandomAccess not implemented!");}}public static void iteratorThroughRandomAccess(List<Integer> list) {long startTime;long endTime;startTime = System.currentTimeMillis();for (int i=0; i<list.size(); i++) {list.get(i);}endTime = System.currentTimeMillis();long interval = endTime - startTime;System.out.println("RandomAccess遍历时间:" + interval+" ms");}public static void iteratorThroughIterator(List<Integer> list) {long startTime;long endTime;startTime = System.currentTimeMillis();for(Iterator<Integer> it = list.iterator(); it.hasNext(); ) {it.next();}endTime = System.currentTimeMillis();long interval = endTime - startTime;System.out.println("Iterator遍历时间:" + interval+" ms");}@SuppressWarnings("unused")public static void iteratorThroughFor(List<Integer> list) {long startTime;long endTime;startTime = System.currentTimeMillis();for(Object obj : list);endTime = System.currentTimeMillis();long interval = endTime - startTime;System.out.println("For循环遍历时间:" + interval+" ms");}
}

每次执行的结果会有一点点区别,在这里我统计了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时,使用随机访问(即通过索引号访问)效率最高,而使用迭代器的效率最低。

4. toArray()异常问题

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

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

[java] view plaincopyprint?
  1. Object[] toArray()
  2. <T> T[] toArray(T[] contents)
Object[] toArray()
<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 plaincopyprint?
  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. // toArray(T[] contents)调用方式二。<span style=”color:#FF6666;”>最常用!</span>
  8. public static Integer[] vectorToArray2(ArrayList<Integer> v) {
  9. Integer[] newText = (Integer[])v.toArray(new Integer[v.size()]);
  10. return newText;
  11. }
  12. // toArray(T[] contents)调用方式三
  13. public static Integer[] vectorToArray3(ArrayList<Integer> v) {
  14. Integer[] newText = new Integer[v.size()];
  15. Integer[] newStrings = (Integer[])v.toArray(newText);
  16. return newStrings;
  17. }
// toArray(T[] contents)调用方式一
public static Integer[] vectorToArray1(ArrayList<Integer> v) {Integer[] newText = new Integer[v.size()];v.toArray(newText);return newText;
}// toArray(T[] contents)调用方式二。<span style="color:#FF6666;">最常用!</span>
public static Integer[] vectorToArray2(ArrayList<Integer> v) {Integer[] newText = (Integer[])v.toArray(new Integer[v.size()]);return newText;
}// toArray(T[] contents)调用方式三
public static Integer[] vectorToArray3(ArrayList<Integer> v) {Integer[] newText = new Integer[v.size()];Integer[] newStrings = (Integer[])v.toArray(newText);return newStrings;
}

三种方式都大同小异。

ArrayList源码就讨论这么多,如有错误,欢迎留言指正~

_____________________________________________________________________________________________________________________________________________________

—–乐于分享,共同进步!

—–更多文章请看:http://blog.csdn.net/eson_15

java集合框架02——ArrayList和源码分析相关推荐

  1. java.lang.ThreadLocal实现原理和源码分析

    java.lang.ThreadLocal实现原理和源码分析 1.ThreadLocal的原理:为每一个线程维护变量的副本.某个线程修改的只是自己的副本. 2.ThreadLocal是如何做到把变量变 ...

  2. 【Java集合框架】ArrayList类方法简明解析(举例说明)

    本文目录 1.API与Java集合框架 2.ArrayList类方法解析 2.1 add() 2.2 addAll() 2.3 clear() 2.4 clone() 2.5 contains() 2 ...

  3. Java集合篇:LinkedList源码分析

    (注:本文内容基于JDK1.6) 一.概述: LinkedList与ArrayList一样实现List接口,只是ArrayList是List接口的大小可变数组的实现,LinkedList是List接口 ...

  4. Java集合框架:ArrayList

    欢迎支持笔者新作:<深入理解Kafka:核心设计与实践原理>和<RabbitMQ实战指南>,同时欢迎关注笔者的微信公众号:朱小厮的博客. 欢迎跳转到本文的原文链接:https: ...

  5. java集合框架05——ArrayList和LinkedList的区别

    前面已经学习完了List部分的源码,主要是ArrayList和LinkedList两部分内容,这一节主要总结下List部分的内容. List概括 先来回顾一下List在Collection中的的框架图 ...

  6. java集合的添加方法_深入理解java集合框架之---------Arraylist集合 -----添加方法

    Arraylist集合 -----添加方法 1.add(E e) 向集合中添加元素 /** * 检查数组容量是否够用 * @param minCapacity */ public void ensur ...

  7. Java集合框架:ArrayList扩容机制解释

    1.java中ArrayList该类的定义 public class ArrayList<E> extends AbstractList<E>implements List&l ...

  8. 深入理解java集合框架之---------Arraylist集合 -----添加方法

    Arraylist集合 -----添加方法 1.add(E e) 向集合中添加元素 /*** 检查数组容量是否够用* @param minCapacity*/public void ensureCap ...

  9. Java集合框架之ArrayList类

    ArrayList是一个泛型数据结构,即对象/引用类型是在<E>里进行确定的(E中定义的必须是对象/引用).例如,定义一个字符串类型的ArrayList为如下格式: ArrayList&l ...

最新文章

  1. 大剑无锋之素数【面试推荐】
  2. etabs数据_etabs使用经验
  3. 笔记-网页内嵌Google地图与地理位置模拟
  4. 类成员的访问修饰符和可访问性
  5. 程序设计导引及在线实践_学院经纬计算学院程序设计基础与实验入选首批国家级一流本科课程...
  6. 【渝粤题库】 陕西师范大学 210021 学前儿童健康教育 作业(专升本)
  7. ABB机器人常用指令
  8. HDU 3533 简单bfs 主要是MLE问题
  9. 波导缝隙天线(二)[搬运]
  10. 魅族4usb计算机连接,魅族MX4如何连接电脑 魅族MX4连接电脑方法
  11. java斜体_设置标签字体用粗体和斜体
  12. Android车辆运动轨迹大数据采集最佳实践
  13. linux配置SVN,添加用户,配置用户组的各个权限教程
  14. 中设智控牵手欧派,助力欧派提升设备管理水平
  15. 图像去噪,深度学习去噪,普通方法
  16. dubbo学习视频资料
  17. Kafka触发Rebalance的场景分析
  18. 基于Netty的联机版坦克大战
  19. 对emp表的一些查询操作
  20. android 静音状态下响铃,教你一招:怎样设置手机在静音状况下的紧急来电提醒!...

热门文章

  1. 12333新农合网上查询_12333新农合查询网站 农村医疗保险缴费查询
  2. Python小白的数学建模课-09 微分方程模型
  3. 【Java】变量的分类(作用域,初始值,生命周期)
  4. Java后端常见问题合集
  5. linux 开启审计服务,Linux审计服务Auditd systemctl重启问题解决
  6. vb6 sp6中文企业版
  7. fedora安装rar解压程序 unrar
  8. 【AI视野·今日NLP 自然语言处理论文速览 第三十一期】Fri, 15 Apr 2022
  9. Windows CE.net 应用开发(教程)----基础篇
  10. vmware里面如何启动BlackBerry 9930模拟器?