ArrayList源码分析

旧城等待, 2022-05-12 08:22 524阅读 0赞
  1. *
  2. public class ArrayList<E> extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, java.io.Serializable

{
private static final long serialVersionUID = 8683452581122892189L;

  1. /** Default initial capacity.
  2. */
  3. private static final int DEFAULT_CAPACITY = 10;
  4. /**
  5. * Shared empty array instance used for empty instances.
  6. */
  7. private static final Object[] EMPTY_ELEMENTDATA = {};
  8. /**
  9. * Shared empty array instance used for default sized empty instances. We
  10. * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  11. * first element is added.
  12. */
  13. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  14. /**
  15. * The array buffer into which the elements of the ArrayList are stored.
  16. * The capacity of the ArrayList is the length of this array buffer. Any
  17. * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
  18. * will be expanded to DEFAULT_CAPACITY when the first element is added.
  19. */
  20. transient Object[] elementData; // non-private to simplify nested class access
  21. /**
  22. * The size of the ArrayList (the number of elements it contains).
  23. *
  24. * @serial
  25. */
  26. private int size;
  27. /**
  28. * Constructs an empty list with the specified initial capacity.
  29. *
  30. * @param initialCapacity the initial capacity of the list
  31. * @throws IllegalArgumentException if the specified initial capacity
  32. * is negative
  33. */
  34. public ArrayList(int initialCapacity) {
  35. if (initialCapacity > 0) {
  36. this.elementData = new Object[initialCapacity];
  37. } else if (initialCapacity == 0) {
  38. this.elementData = EMPTY_ELEMENTDATA;
  39. } else {
  40. throw new IllegalArgumentException("Illegal Capacity: "+
  41. initialCapacity);
  42. }
  43. }
  44. /**
  45. * Constructs an empty list with an initial capacity of ten.
  46. */
  47. public ArrayList() {
  48. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  49. }
  50. /**
  51. * Constructs a list containing the elements of the specified
  52. * collection, in the order they are returned by the collection's
  53. * iterator.
  54. *
  55. * @param c the collection whose elements are to be placed into this list
  56. * @throws NullPointerException if the specified collection is null
  57. */
  58. public ArrayList(Collection<? extends E> c) {
  59. elementData = c.toArray();
  60. if ((size = elementData.length) != 0) {
  61. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  62. if (elementData.getClass() != Object[].class)
  63. elementData = Arrays.copyOf(elementData, size, Object[].class);
  64. } else {
  65. // replace with empty array.
  66. this.elementData = EMPTY_ELEMENTDATA;
  67. }
  68. }
  69. /**
  70. * Trims the capacity of this <tt>ArrayList</tt> instance to be the
  71. * list's current size. An application can use this operation to minimize
  72. * the storage of an <tt>ArrayList</tt> instance.
  73. */
  74. public void trimToSize() {
  75. modCount++;
  76. if (size < elementData.length) {
  77. elementData = (size == 0)
  78. ? EMPTY_ELEMENTDATA
  79. : Arrays.copyOf(elementData, size);
  80. }
  81. }
  82. /**
  83. * Increases the capacity of this <tt>ArrayList</tt> instance, if
  84. * necessary, to ensure that it can hold at least the number of elements
  85. * specified by the minimum capacity argument.
  86. *
  87. * @param minCapacity the desired minimum capacity
  88. */
  89. public void ensureCapacity(int minCapacity) {
  90. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
  91. // any size if not default element table
  92. ? 0
  93. // larger than default for default empty table. It's already
  94. // supposed to be at default size.
  95. : DEFAULT_CAPACITY;
  96. if (minCapacity > minExpand) {
  97. ensureExplicitCapacity(minCapacity);
  98. }
  99. }
  100. private static int calculateCapacity(Object[] elementData, int minCapacity) {
  101. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  102. return Math.max(DEFAULT_CAPACITY, minCapacity);
  103. }
  104. return minCapacity;
  105. }
  106. private void ensureCapacityInternal(int minCapacity) {
  107. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  108. }
  109. private void ensureExplicitCapacity(int minCapacity) {
  110. modCount++;
  111. // overflow-conscious code
  112. if (minCapacity - elementData.length > 0)
  113. grow(minCapacity);
  114. }
  115. /**
  116. * The maximum size of array to allocate.
  117. * Some VMs reserve some header words in an array.
  118. * Attempts to allocate larger arrays may result in
  119. * OutOfMemoryError: Requested array size exceeds VM limit
  120. */
  121. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  122. /**
  123. * Increases the capacity to ensure that it can hold at least the
  124. * number of elements specified by the minimum capacity argument.
  125. *
  126. * @param minCapacity the desired minimum capacity
  127. */
  128. private void grow(int minCapacity) {
  129. // overflow-conscious code
  130. int oldCapacity = elementData.length;
  131. int newCapacity = oldCapacity + (oldCapacity >> 1);
  132. if (newCapacity - minCapacity < 0)
  133. newCapacity = minCapacity;
  134. if (newCapacity - MAX_ARRAY_SIZE > 0)
  135. newCapacity = hugeCapacity(minCapacity);
  136. // minCapacity is usually close to size, so this is a win:
  137. elementData = Arrays.copyOf(elementData, newCapacity);
  138. }
  139. private static int hugeCapacity(int minCapacity) {
  140. if (minCapacity < 0) // overflow
  141. throw new OutOfMemoryError();
  142. return (minCapacity > MAX_ARRAY_SIZE) ?
  143. Integer.MAX_VALUE :
  144. MAX_ARRAY_SIZE;
  145. }
  146. /**
  147. * Returns the number of elements in this list.
  148. *
  149. * @return the number of elements in this list
  150. */
  151. public int size() {
  152. return size;
  153. }
  154. /**
  155. * Returns <tt>true</tt> if this list contains no elements.
  156. *
  157. * @return <tt>true</tt> if this list contains no elements
  158. */
  159. public boolean isEmpty() {
  160. return size == 0;
  161. }
  162. /**
  163. * Returns <tt>true</tt> if this list contains the specified element.
  164. * More formally, returns <tt>true</tt> if and only if this list contains
  165. * at least one element <tt>e</tt> such that
  166. * <tt>(o==null ? e==null : o.equals(e))</tt>.
  167. *
  168. * @param o element whose presence in this list is to be tested
  169. * @return <tt>true</tt> if this list contains the specified element
  170. */
  171. public boolean contains(Object o) {
  172. return indexOf(o) >= 0;
  173. }
  174. /**
  175. * Returns the index of the first occurrence of the specified element
  176. * in this list, or -1 if this list does not contain the element.
  177. * More formally, returns the lowest index <tt>i</tt> such that
  178. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  179. * or -1 if there is no such index.
  180. */
  181. public int indexOf(Object o) {
  182. if (o == null) {
  183. for (int i = 0; i < size; i++)
  184. if (elementData[i]==null)
  185. return i;
  186. } else {
  187. for (int i = 0; i < size; i++)
  188. if (o.equals(elementData[i]))
  189. return i;
  190. }
  191. return -1;
  192. }
  193. /**
  194. * Returns the index of the last occurrence of the specified element
  195. * in this list, or -1 if this list does not contain the element.
  196. * More formally, returns the highest index <tt>i</tt> such that
  197. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  198. * or -1 if there is no such index.
  199. */
  200. public int lastIndexOf(Object o) {
  201. if (o == null) {
  202. for (int i = size-1; i >= 0; i--)
  203. if (elementData[i]==null)
  204. return i;
  205. } else {
  206. for (int i = size-1; i >= 0; i--)
  207. if (o.equals(elementData[i]))
  208. return i;
  209. }
  210. return -1;
  211. }
  212. /**
  213. * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
  214. * elements themselves are not copied.)
  215. *
  216. * @return a clone of this <tt>ArrayList</tt> instance
  217. */
  218. public Object clone() {
  219. try {
  220. ArrayList<?> v = (ArrayList<?>) super.clone();
  221. v.elementData = Arrays.copyOf(elementData, size);
  222. v.modCount = 0;
  223. return v;
  224. } catch (CloneNotSupportedException e) {
  225. // this shouldn't happen, since we are Cloneable
  226. throw new InternalError(e);
  227. }
  228. }
  229. /**
  230. * Returns an array containing all of the elements in this list
  231. * in proper sequence (from first to last element).
  232. *
  233. * <p>The returned array will be "safe" in that no references to it are
  234. * maintained by this list. (In other words, this method must allocate
  235. * a new array). The caller is thus free to modify the returned array.
  236. *
  237. * <p>This method acts as bridge between array-based and collection-based
  238. * APIs.
  239. *
  240. * @return an array containing all of the elements in this list in
  241. * proper sequence
  242. */
  243. public Object[] toArray() {
  244. return Arrays.copyOf(elementData, size);
  245. }
  246. /**
  247. * Returns an array containing all of the elements in this list in proper
  248. * sequence (from first to last element); the runtime type of the returned
  249. * array is that of the specified array. If the list fits in the
  250. * specified array, it is returned therein. Otherwise, a new array is
  251. * allocated with the runtime type of the specified array and the size of
  252. * this list.
  253. *
  254. * <p>If the list fits in the specified array with room to spare
  255. * (i.e., the array has more elements than the list), the element in
  256. * the array immediately following the end of the collection is set to
  257. * <tt>null</tt>. (This is useful in determining the length of the
  258. * list <i>only</i> if the caller knows that the list does not contain
  259. * any null elements.)
  260. *
  261. * @param a the array into which the elements of the list are to
  262. * be stored, if it is big enough; otherwise, a new array of the
  263. * same runtime type is allocated for this purpose.
  264. * @return an array containing the elements of the list
  265. * @throws ArrayStoreException if the runtime type of the specified array
  266. * is not a supertype of the runtime type of every element in
  267. * this list
  268. * @throws NullPointerException if the specified array is null
  269. */
  270. @SuppressWarnings("unchecked")
  271. public <T> T[] toArray(T[] a) {
  272. if (a.length < size)
  273. // Make a new array of a's runtime type, but my contents:
  274. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  275. System.arraycopy(elementData, 0, a, 0, size);
  276. if (a.length > size)
  277. a[size] = null;
  278. return a;
  279. }
  280. // Positional Access Operations
  281. @SuppressWarnings("unchecked")
  282. E elementData(int index) {
  283. return (E) elementData[index];
  284. }
  285. /**
  286. * Returns the element at the specified position in this list.
  287. *
  288. * @param index index of the element to return
  289. * @return the element at the specified position in this list
  290. * @throws IndexOutOfBoundsException {@inheritDoc}
  291. */
  292. public E get(int index) {
  293. rangeCheck(index);
  294. return elementData(index);
  295. }
  296. /**
  297. * Replaces the element at the specified position in this list with
  298. * the specified element.
  299. *
  300. * @param index index of the element to replace
  301. * @param element element to be stored at the specified position
  302. * @return the element previously at the specified position
  303. * @throws IndexOutOfBoundsException {@inheritDoc}
  304. */
  305. public E set(int index, E element) {
  306. rangeCheck(index);
  307. E oldValue = elementData(index);
  308. elementData[index] = element;
  309. return oldValue;
  310. }
  311. /**
  312. * Appends the specified element to the end of this list.
  313. *
  314. * @param e element to be appended to this list
  315. * @return <tt>true</tt> (as specified by {@link Collection#add})
  316. */
  317. public boolean add(E e) {
  318. ensureCapacityInternal(size + 1); // Increments modCount!!
  319. elementData[size++] = e;
  320. return true;
  321. }
  322. /**
  323. * Inserts the specified element at the specified position in this
  324. * list. Shifts the element currently at that position (if any) and
  325. * any subsequent elements to the right (adds one to their indices).
  326. *
  327. * @param index index at which the specified element is to be inserted
  328. * @param element element to be inserted
  329. * @throws IndexOutOfBoundsException {@inheritDoc}
  330. */
  331. public void add(int index, E element) {
  332. rangeCheckForAdd(index);
  333. ensureCapacityInternal(size + 1); // Increments modCount!!
  334. System.arraycopy(elementData, index, elementData, index + 1,
  335. size - index);
  336. elementData[index] = element;
  337. size++;
  338. }
  339. /**
  340. * Removes the element at the specified position in this list.
  341. * Shifts any subsequent elements to the left (subtracts one from their
  342. * indices).
  343. *
  344. * @param index the index of the element to be removed
  345. * @return the element that was removed from the list
  346. * @throws IndexOutOfBoundsException {@inheritDoc}
  347. */
  348. public E remove(int index) {
  349. rangeCheck(index);
  350. modCount++;
  351. E oldValue = elementData(index);
  352. int numMoved = size - index - 1;
  353. if (numMoved > 0)
  354. System.arraycopy(elementData, index+1, elementData, index,
  355. numMoved);
  356. elementData[--size] = null; // clear to let GC do its work
  357. return oldValue;
  358. }
  359. /**
  360. * Removes the first occurrence of the specified element from this list,
  361. * if it is present. If the list does not contain the element, it is
  362. * unchanged. More formally, removes the element with the lowest index
  363. * <tt>i</tt> such that
  364. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
  365. * (if such an element exists). Returns <tt>true</tt> if this list
  366. * contained the specified element (or equivalently, if this list
  367. * changed as a result of the call).
  368. *
  369. * @param o element to be removed from this list, if present
  370. * @return <tt>true</tt> if this list contained the specified element
  371. */
  372. public boolean remove(Object o) {
  373. if (o == null) {
  374. for (int index = 0; index < size; index++)
  375. if (elementData[index] == null) {
  376. fastRemove(index);
  377. return true;
  378. }
  379. } else {
  380. for (int index = 0; index < size; index++)
  381. if (o.equals(elementData[index])) {
  382. fastRemove(index);
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. /*
  389. * Private remove method that skips bounds checking and does not
  390. * return the value removed.
  391. */
  392. private void fastRemove(int index) {
  393. modCount++;
  394. int numMoved = size - index - 1;
  395. if (numMoved > 0)
  396. System.arraycopy(elementData, index+1, elementData, index,
  397. numMoved);
  398. elementData[--size] = null; // clear to let GC do its work
  399. }
  400. /**
  401. * Removes all of the elements from this list. The list will
  402. * be empty after this call returns.
  403. */
  404. public void clear() {
  405. modCount++;
  406. // clear to let GC do its work
  407. for (int i = 0; i < size; i++)
  408. elementData[i] = null;
  409. size = 0;
  410. }
  411. /**
  412. * Appends all of the elements in the specified collection to the end of
  413. * this list, in the order that they are returned by the
  414. * specified collection's Iterator. The behavior of this operation is
  415. * undefined if the specified collection is modified while the operation
  416. * is in progress. (This implies that the behavior of this call is
  417. * undefined if the specified collection is this list, and this
  418. * list is nonempty.)
  419. *
  420. * @param c collection containing elements to be added to this list
  421. * @return <tt>true</tt> if this list changed as a result of the call
  422. * @throws NullPointerException if the specified collection is null
  423. */
  424. public boolean addAll(Collection<? extends E> c) {
  425. Object[] a = c.toArray();
  426. int numNew = a.length;
  427. ensureCapacityInternal(size + numNew); // Increments modCount
  428. System.arraycopy(a, 0, elementData, size, numNew);
  429. size += numNew;
  430. return numNew != 0;
  431. }
  432. /**
  433. * Inserts all of the elements in the specified collection into this
  434. * list, starting at the specified position. Shifts the element
  435. * currently at that position (if any) and any subsequent elements to
  436. * the right (increases their indices). The new elements will appear
  437. * in the list in the order that they are returned by the
  438. * specified collection's iterator.
  439. *
  440. * @param index index at which to insert the first element from the
  441. * specified collection
  442. * @param c collection containing elements to be added to this list
  443. * @return <tt>true</tt> if this list changed as a result of the call
  444. * @throws IndexOutOfBoundsException {@inheritDoc}
  445. * @throws NullPointerException if the specified collection is null
  446. */
  447. public boolean addAll(int index, Collection<? extends E> c) {
  448. rangeCheckForAdd(index);
  449. Object[] a = c.toArray();
  450. int numNew = a.length;
  451. ensureCapacityInternal(size + numNew); // Increments modCount
  452. int numMoved = size - index;
  453. if (numMoved > 0)
  454. System.arraycopy(elementData, index, elementData, index + numNew,
  455. numMoved);
  456. System.arraycopy(a, 0, elementData, index, numNew);
  457. size += numNew;
  458. return numNew != 0;
  459. }
  460. /**
  461. * Removes from this list all of the elements whose index is between
  462. * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
  463. * Shifts any succeeding elements to the left (reduces their index).
  464. * This call shortens the list by {@code (toIndex - fromIndex)} elements.
  465. * (If {@code toIndex==fromIndex}, this operation has no effect.)
  466. *
  467. * @throws IndexOutOfBoundsException if {@code fromIndex} or
  468. * {@code toIndex} is out of range
  469. * ({@code fromIndex < 0 ||
  470. * fromIndex >= size() ||
  471. * toIndex > size() ||
  472. * toIndex < fromIndex})
  473. */
  474. protected void removeRange(int fromIndex, int toIndex) {
  475. modCount++;
  476. int numMoved = size - toIndex;
  477. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  478. numMoved);
  479. // clear to let GC do its work
  480. int newSize = size - (toIndex-fromIndex);
  481. for (int i = newSize; i < size; i++) {
  482. elementData[i] = null;
  483. }
  484. size = newSize;
  485. }
  486. /**
  487. * Checks if the given index is in range. If not, throws an appropriate
  488. * runtime exception. This method does *not* check if the index is
  489. * negative: It is always used immediately prior to an array access,
  490. * which throws an ArrayIndexOutOfBoundsException if index is negative.
  491. */
  492. private void rangeCheck(int index) {
  493. if (index >= size)
  494. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  495. }
  496. /**
  497. * A version of rangeCheck used by add and addAll.
  498. */
  499. private void rangeCheckForAdd(int index) {
  500. if (index > size || index < 0)
  501. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  502. }
  503. /**
  504. * Constructs an IndexOutOfBoundsException detail message.
  505. * Of the many possible refactorings of the error handling code,
  506. * this "outlining" performs best with both server and client VMs.
  507. */
  508. private String outOfBoundsMsg(int index) {
  509. return "Index: "+index+", Size: "+size;
  510. }
  511. /**
  512. * Removes from this list all of its elements that are contained in the
  513. * specified collection.
  514. *
  515. * @param c collection containing elements to be removed from this list
  516. * @return {@code true} if this list changed as a result of the call
  517. * @throws ClassCastException if the class of an element of this list
  518. * is incompatible with the specified collection
  519. * (<a href="Collection.html#optional-restrictions">optional</a>)
  520. * @throws NullPointerException if this list contains a null element and the
  521. * specified collection does not permit null elements
  522. * (<a href="Collection.html#optional-restrictions">optional</a>),
  523. * or if the specified collection is null
  524. * @see Collection#contains(Object)
  525. */
  526. public boolean removeAll(Collection<?> c) {
  527. Objects.requireNonNull(c);
  528. return batchRemove(c, false);
  529. }
  530. /**
  531. * Retains only the elements in this list that are contained in the
  532. * specified collection. In other words, removes from this list all
  533. * of its elements that are not contained in the specified collection.
  534. *
  535. * @param c collection containing elements to be retained in this list
  536. * @return {@code true} if this list changed as a result of the call
  537. * @throws ClassCastException if the class of an element of this list
  538. * is incompatible with the specified collection
  539. * (<a href="Collection.html#optional-restrictions">optional</a>)
  540. * @throws NullPointerException if this list contains a null element and the
  541. * specified collection does not permit null elements
  542. * (<a href="Collection.html#optional-restrictions">optional</a>),
  543. * or if the specified collection is null
  544. * @see Collection#contains(Object)
  545. */
  546. public boolean retainAll(Collection<?> c) {
  547. Objects.requireNonNull(c);
  548. return batchRemove(c, true);
  549. }
  550. private boolean batchRemove(Collection<?> c, boolean complement) {
  551. final Object[] elementData = this.elementData;
  552. int r = 0, w = 0;
  553. boolean modified = false;
  554. try {
  555. for (; r < size; r++)
  556. if (c.contains(elementData[r]) == complement)
  557. elementData[w++] = elementData[r];
  558. } finally {
  559. // Preserve behavioral compatibility with AbstractCollection,
  560. // even if c.contains() throws.
  561. if (r != size) {
  562. System.arraycopy(elementData, r,
  563. elementData, w,
  564. size - r);
  565. w += size - r;
  566. }
  567. if (w != size) {
  568. // clear to let GC do its work
  569. for (int i = w; i < size; i++)
  570. elementData[i] = null;
  571. modCount += size - w;
  572. size = w;
  573. modified = true;
  574. }
  575. }
  576. return modified;
  577. }
  578. /**
  579. * Save the state of the <tt>ArrayList</tt> instance to a stream (that
  580. * is, serialize it).
  581. *
  582. * @serialData The length of the array backing the <tt>ArrayList</tt>
  583. * instance is emitted (int), followed by all of its elements
  584. * (each an <tt>Object</tt>) in the proper order.
  585. */
  586. private void writeObject(java.io.ObjectOutputStream s)
  587. throws java.io.IOException{
  588. // Write out element count, and any hidden stuff
  589. int expectedModCount = modCount;
  590. s.defaultWriteObject();
  591. // Write out size as capacity for behavioural compatibility with clone()
  592. s.writeInt(size);
  593. // Write out all elements in the proper order.
  594. for (int i=0; i<size; i++) {
  595. s.writeObject(elementData[i]);
  596. }
  597. if (modCount != expectedModCount) {
  598. throw new ConcurrentModificationException();
  599. }
  600. }
  601. /**
  602. * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
  603. * deserialize it).
  604. */
  605. private void readObject(java.io.ObjectInputStream s)
  606. throws java.io.IOException, ClassNotFoundException {
  607. elementData = EMPTY_ELEMENTDATA;
  608. // Read in size, and any hidden stuff
  609. s.defaultReadObject();
  610. // Read in capacity
  611. s.readInt(); // ignored
  612. if (size > 0) {
  613. // be like clone(), allocate array based upon size not capacity
  614. int capacity = calculateCapacity(elementData, size);
  615. SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
  616. ensureCapacityInternal(size);
  617. Object[] a = elementData;
  618. // Read in all elements in the proper order.
  619. for (int i=0; i<size; i++) {
  620. a[i] = s.readObject();
  621. }
  622. }
  623. }
  624. /**
  625. * Returns a list iterator over the elements in this list (in proper
  626. * sequence), starting at the specified position in the list.
  627. * The specified index indicates the first element that would be
  628. * returned by an initial call to {@link ListIterator#next next}.
  629. * An initial call to {@link ListIterator#previous previous} would
  630. * return the element with the specified index minus one.
  631. *
  632. * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
  633. *
  634. * @throws IndexOutOfBoundsException {@inheritDoc}
  635. */
  636. public ListIterator<E> listIterator(int index) {
  637. if (index < 0 || index > size)
  638. throw new IndexOutOfBoundsException("Index: "+index);
  639. return new ListItr(index);
  640. }
  641. /**
  642. * Returns a list iterator over the elements in this list (in proper
  643. * sequence).
  644. *
  645. * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
  646. *
  647. * @see #listIterator(int)
  648. */
  649. public ListIterator<E> listIterator() {
  650. return new ListItr(0);
  651. }
  652. /**
  653. * Returns an iterator over the elements in this list in proper sequence.
  654. *
  655. * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
  656. *
  657. * @return an iterator over the elements in this list in proper sequence
  658. */
  659. public Iterator<E> iterator() {
  660. return new Itr();
  661. }
  662. /**
  663. * An optimized version of AbstractList.Itr
  664. */
  665. private class Itr implements Iterator<E> {
  666. int cursor; // index of next element to return
  667. int lastRet = -1; // index of last element returned; -1 if no such
  668. int expectedModCount = modCount;
  669. Itr() {}
  670. public boolean hasNext() {
  671. return cursor != size;
  672. }
  673. @SuppressWarnings("unchecked")
  674. public E next() {
  675. checkForComodification();
  676. int i = cursor;
  677. if (i >= size)
  678. throw new NoSuchElementException();
  679. Object[] elementData = ArrayList.this.elementData;
  680. if (i >= elementData.length)
  681. throw new ConcurrentModificationException();
  682. cursor = i + 1;
  683. return (E) elementData[lastRet = i];
  684. }
  685. public void remove() {
  686. if (lastRet < 0)
  687. throw new IllegalStateException();
  688. checkForComodification();
  689. try {
  690. ArrayList.this.remove(lastRet);
  691. cursor = lastRet;
  692. lastRet = -1;
  693. expectedModCount = modCount;
  694. } catch (IndexOutOfBoundsException ex) {
  695. throw new ConcurrentModificationException();
  696. }
  697. }
  698. @Override
  699. @SuppressWarnings("unchecked")
  700. public void forEachRemaining(Consumer<? super E> consumer) {
  701. Objects.requireNonNull(consumer);
  702. final int size = ArrayList.this.size;
  703. int i = cursor;
  704. if (i >= size) {
  705. return;
  706. }
  707. final Object[] elementData = ArrayList.this.elementData;
  708. if (i >= elementData.length) {
  709. throw new ConcurrentModificationException();
  710. }
  711. while (i != size && modCount == expectedModCount) {
  712. consumer.accept((E) elementData[i++]);
  713. }
  714. // update once at end of iteration to reduce heap write traffic
  715. cursor = i;
  716. lastRet = i - 1;
  717. checkForComodification();
  718. }
  719. final void checkForComodification() {
  720. if (modCount != expectedModCount)
  721. throw new ConcurrentModificationException();
  722. }
  723. }
  724. /**
  725. * An optimized version of AbstractList.ListItr
  726. */
  727. private class ListItr extends Itr implements ListIterator<E> {
  728. ListItr(int index) {
  729. super();
  730. cursor = index;
  731. }
  732. public boolean hasPrevious() {
  733. return cursor != 0;
  734. }
  735. public int nextIndex() {
  736. return cursor;
  737. }
  738. public int previousIndex() {
  739. return cursor - 1;
  740. }
  741. @SuppressWarnings("unchecked")
  742. public E previous() {
  743. checkForComodification();
  744. int i = cursor - 1;
  745. if (i < 0)
  746. throw new NoSuchElementException();
  747. Object[] elementData = ArrayList.this.elementData;
  748. if (i >= elementData.length)
  749. throw new ConcurrentModificationException();
  750. cursor = i;
  751. return (E) elementData[lastRet = i];
  752. }
  753. public void set(E e) {
  754. if (lastRet < 0)
  755. throw new IllegalStateException();
  756. checkForComodification();
  757. try {
  758. ArrayList.this.set(lastRet, e);
  759. } catch (IndexOutOfBoundsException ex) {
  760. throw new ConcurrentModificationException();
  761. }
  762. }
  763. public void add(E e) {
  764. checkForComodification();
  765. try {
  766. int i = cursor;
  767. ArrayList.this.add(i, e);
  768. cursor = i + 1;
  769. lastRet = -1;
  770. expectedModCount = modCount;
  771. } catch (IndexOutOfBoundsException ex) {
  772. throw new ConcurrentModificationException();
  773. }
  774. }
  775. }
  776. /**
  777. * Returns a view of the portion of this list between the specified
  778. * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
  779. * {@code fromIndex} and {@code toIndex} are equal, the returned list is
  780. * empty.) The returned list is backed by this list, so non-structural
  781. * changes in the returned list are reflected in this list, and vice-versa.
  782. * The returned list supports all of the optional list operations.
  783. *
  784. * <p>This method eliminates the need for explicit range operations (of
  785. * the sort that commonly exist for arrays). Any operation that expects
  786. * a list can be used as a range operation by passing a subList view
  787. * instead of a whole list. For example, the following idiom
  788. * removes a range of elements from a list:
  789. * <pre>
  790. * list.subList(from, to).clear();
  791. * </pre>
  792. * Similar idioms may be constructed for {@link #indexOf(Object)} and
  793. * {@link #lastIndexOf(Object)}, and all of the algorithms in the
  794. * {@link Collections} class can be applied to a subList.
  795. *
  796. * <p>The semantics of the list returned by this method become undefined if
  797. * the backing list (i.e., this list) is <i>structurally modified</i> in
  798. * any way other than via the returned list. (Structural modifications are
  799. * those that change the size of this list, or otherwise perturb it in such
  800. * a fashion that iterations in progress may yield incorrect results.)
  801. *
  802. * @throws IndexOutOfBoundsException {@inheritDoc}
  803. * @throws IllegalArgumentException {@inheritDoc}
  804. */
  805. public List<E> subList(int fromIndex, int toIndex) {
  806. subListRangeCheck(fromIndex, toIndex, size);
  807. return new SubList(this, 0, fromIndex, toIndex);
  808. }
  809. static void subListRangeCheck(int fromIndex, int toIndex, int size) {
  810. if (fromIndex < 0)
  811. throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
  812. if (toIndex > size)
  813. throw new IndexOutOfBoundsException("toIndex = " + toIndex);
  814. if (fromIndex > toIndex)
  815. throw new IllegalArgumentException("fromIndex(" + fromIndex +
  816. ") > toIndex(" + toIndex + ")");
  817. }
  818. private class SubList extends AbstractList<E> implements RandomAccess {
  819. private final AbstractList<E> parent;
  820. private final int parentOffset;
  821. private final int offset;
  822. int size;
  823. SubList(AbstractList<E> parent,
  824. int offset, int fromIndex, int toIndex) {
  825. this.parent = parent;
  826. this.parentOffset = fromIndex;
  827. this.offset = offset + fromIndex;
  828. this.size = toIndex - fromIndex;
  829. this.modCount = ArrayList.this.modCount;
  830. }
  831. public E set(int index, E e) {
  832. rangeCheck(index);
  833. checkForComodification();
  834. E oldValue = ArrayList.this.elementData(offset + index);
  835. ArrayList.this.elementData[offset + index] = e;
  836. return oldValue;
  837. }
  838. public E get(int index) {
  839. rangeCheck(index);
  840. checkForComodification();
  841. return ArrayList.this.elementData(offset + index);
  842. }
  843. public int size() {
  844. checkForComodification();
  845. return this.size;
  846. }
  847. public void add(int index, E e) {
  848. rangeCheckForAdd(index);
  849. checkForComodification();
  850. parent.add(parentOffset + index, e);
  851. this.modCount = parent.modCount;
  852. this.size++;
  853. }
  854. public E remove(int index) {
  855. rangeCheck(index);
  856. checkForComodification();
  857. E result = parent.remove(parentOffset + index);
  858. this.modCount = parent.modCount;
  859. this.size--;
  860. return result;
  861. }
  862. protected void removeRange(int fromIndex, int toIndex) {
  863. checkForComodification();
  864. parent.removeRange(parentOffset + fromIndex,
  865. parentOffset + toIndex);
  866. this.modCount = parent.modCount;
  867. this.size -= toIndex - fromIndex;
  868. }
  869. public boolean addAll(Collection<? extends E> c) {
  870. return addAll(this.size, c);
  871. }
  872. public boolean addAll(int index, Collection<? extends E> c) {
  873. rangeCheckForAdd(index);
  874. int cSize = c.size();
  875. if (cSize==0)
  876. return false;
  877. checkForComodification();
  878. parent.addAll(parentOffset + index, c);
  879. this.modCount = parent.modCount;
  880. this.size += cSize;
  881. return true;
  882. }
  883. public Iterator<E> iterator() {
  884. return listIterator();
  885. }
  886. public ListIterator<E> listIterator(final int index) {
  887. checkForComodification();
  888. rangeCheckForAdd(index);
  889. final int offset = this.offset;
  890. return new ListIterator<E>() {
  891. int cursor = index;
  892. int lastRet = -1;
  893. int expectedModCount = ArrayList.this.modCount;
  894. public boolean hasNext() {
  895. return cursor != SubList.this.size;
  896. }
  897. @SuppressWarnings("unchecked")
  898. public E next() {
  899. checkForComodification();
  900. int i = cursor;
  901. if (i >= SubList.this.size)
  902. throw new NoSuchElementException();
  903. Object[] elementData = ArrayList.this.elementData;
  904. if (offset + i >= elementData.length)
  905. throw new ConcurrentModificationException();
  906. cursor = i + 1;
  907. return (E) elementData[offset + (lastRet = i)];
  908. }
  909. public boolean hasPrevious() {
  910. return cursor != 0;
  911. }
  912. @SuppressWarnings("unchecked")
  913. public E previous() {
  914. checkForComodification();
  915. int i = cursor - 1;
  916. if (i < 0)
  917. throw new NoSuchElementException();
  918. Object[] elementData = ArrayList.this.elementData;
  919. if (offset + i >= elementData.length)
  920. throw new ConcurrentModificationException();
  921. cursor = i;
  922. return (E) elementData[offset + (lastRet = i)];
  923. }
  924. @SuppressWarnings("unchecked")
  925. public void forEachRemaining(Consumer<? super E> consumer) {
  926. Objects.requireNonNull(consumer);
  927. final int size = SubList.this.size;
  928. int i = cursor;
  929. if (i >= size) {
  930. return;
  931. }
  932. final Object[] elementData = ArrayList.this.elementData;
  933. if (offset + i >= elementData.length) {
  934. throw new ConcurrentModificationException();
  935. }
  936. while (i != size && modCount == expectedModCount) {
  937. consumer.accept((E) elementData[offset + (i++)]);
  938. }
  939. // update once at end of iteration to reduce heap write traffic
  940. lastRet = cursor = i;
  941. checkForComodification();
  942. }
  943. public int nextIndex() {
  944. return cursor;
  945. }
  946. public int previousIndex() {
  947. return cursor - 1;
  948. }
  949. public void remove() {
  950. if (lastRet < 0)
  951. throw new IllegalStateException();
  952. checkForComodification();
  953. try {
  954. SubList.this.remove(lastRet);
  955. cursor = lastRet;
  956. lastRet = -1;
  957. expectedModCount = ArrayList.this.modCount;
  958. } catch (IndexOutOfBoundsException ex) {
  959. throw new ConcurrentModificationException();
  960. }
  961. }
  962. public void set(E e) {
  963. if (lastRet < 0)
  964. throw new IllegalStateException();
  965. checkForComodification();
  966. try {
  967. ArrayList.this.set(offset + lastRet, e);
  968. } catch (IndexOutOfBoundsException ex) {
  969. throw new ConcurrentModificationException();
  970. }
  971. }
  972. public void add(E e) {
  973. checkForComodification();
  974. try {
  975. int i = cursor;
  976. SubList.this.add(i, e);
  977. cursor = i + 1;
  978. lastRet = -1;
  979. expectedModCount = ArrayList.this.modCount;
  980. } catch (IndexOutOfBoundsException ex) {
  981. throw new ConcurrentModificationException();
  982. }
  983. }
  984. final void checkForComodification() {
  985. if (expectedModCount != ArrayList.this.modCount)
  986. throw new ConcurrentModificationException();
  987. }
  988. };
  989. }
  990. public List<E> subList(int fromIndex, int toIndex) {
  991. subListRangeCheck(fromIndex, toIndex, size);
  992. return new SubList(this, offset, fromIndex, toIndex);
  993. }
  994. private void rangeCheck(int index) {
  995. if (index < 0 || index >= this.size)
  996. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  997. }
  998. private void rangeCheckForAdd(int index) {
  999. if (index < 0 || index > this.size)
  1000. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  1001. }
  1002. private String outOfBoundsMsg(int index) {
  1003. return "Index: "+index+", Size: "+this.size;
  1004. }
  1005. private void checkForComodification() {
  1006. if (ArrayList.this.modCount != this.modCount)
  1007. throw new ConcurrentModificationException();
  1008. }
  1009. public Spliterator<E> spliterator() {
  1010. checkForComodification();
  1011. return new ArrayListSpliterator<E>(ArrayList.this, offset,
  1012. offset + this.size, this.modCount);
  1013. }
  1014. }
  1015. @Override
  1016. public void forEach(Consumer<? super E> action) {
  1017. Objects.requireNonNull(action);
  1018. final int expectedModCount = modCount;
  1019. @SuppressWarnings("unchecked")
  1020. final E[] elementData = (E[]) this.elementData;
  1021. final int size = this.size;
  1022. for (int i=0; modCount == expectedModCount && i < size; i++) {
  1023. action.accept(elementData[i]);
  1024. }
  1025. if (modCount != expectedModCount) {
  1026. throw new ConcurrentModificationException();
  1027. }
  1028. }
  1029. /**
  1030. * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
  1031. * and <em>fail-fast</em> {@link Spliterator} over the elements in this
  1032. * list.
  1033. *
  1034. * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
  1035. * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
  1036. * Overriding implementations should document the reporting of additional
  1037. * characteristic values.
  1038. *
  1039. * @return a {@code Spliterator} over the elements in this list
  1040. * @since 1.8
  1041. */
  1042. @Override
  1043. public Spliterator<E> spliterator() {
  1044. return new ArrayListSpliterator<>(this, 0, -1, 0);
  1045. }
  1046. /** Index-based split-by-two, lazily initialized Spliterator */
  1047. static final class ArrayListSpliterator<E> implements Spliterator<E> {
  1048. /*
  1049. * If ArrayLists were immutable, or structurally immutable (no
  1050. * adds, removes, etc), we could implement their spliterators
  1051. * with Arrays.spliterator. Instead we detect as much
  1052. * interference during traversal as practical without
  1053. * sacrificing much performance. We rely primarily on
  1054. * modCounts. These are not guaranteed to detect concurrency
  1055. * violations, and are sometimes overly conservative about
  1056. * within-thread interference, but detect enough problems to
  1057. * be worthwhile in practice. To carry this out, we (1) lazily
  1058. * initialize fence and expectedModCount until the latest
  1059. * point that we need to commit to the state we are checking
  1060. * against; thus improving precision. (This doesn't apply to
  1061. * SubLists, that create spliterators with current non-lazy
  1062. * values). (2) We perform only a single
  1063. * ConcurrentModificationException check at the end of forEach
  1064. * (the most performance-sensitive method). When using forEach
  1065. * (as opposed to iterators), we can normally only detect
  1066. * interference after actions, not before. Further
  1067. * CME-triggering checks apply to all other possible
  1068. * violations of assumptions for example null or too-small
  1069. * elementData array given its size(), that could only have
  1070. * occurred due to interference. This allows the inner loop
  1071. * of forEach to run without any further checks, and
  1072. * simplifies lambda-resolution. While this does entail a
  1073. * number of checks, note that in the common case of
  1074. * list.stream().forEach(a), no checks or other computation
  1075. * occur anywhere other than inside forEach itself. The other
  1076. * less-often-used methods cannot take advantage of most of
  1077. * these streamlinings.
  1078. */
  1079. private final ArrayList<E> list;
  1080. private int index; // current index, modified on advance/split
  1081. private int fence; // -1 until used; then one past last index
  1082. private int expectedModCount; // initialized when fence set
  1083. /** Create new spliterator covering the given range */
  1084. ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
  1085. int expectedModCount) {
  1086. this.list = list; // OK if null unless traversed
  1087. this.index = origin;
  1088. this.fence = fence;
  1089. this.expectedModCount = expectedModCount;
  1090. }
  1091. private int getFence() { // initialize fence to size on first use
  1092. int hi; // (a specialized variant appears in method forEach)
  1093. ArrayList<E> lst;
  1094. if ((hi = fence) < 0) {
  1095. if ((lst = list) == null)
  1096. hi = fence = 0;
  1097. else {
  1098. expectedModCount = lst.modCount;
  1099. hi = fence = lst.size;
  1100. }
  1101. }
  1102. return hi;
  1103. }
  1104. public ArrayListSpliterator<E> trySplit() {
  1105. int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
  1106. return (lo >= mid) ? null : // divide range in half unless too small
  1107. new ArrayListSpliterator<E>(list, lo, index = mid,
  1108. expectedModCount);
  1109. }
  1110. public boolean tryAdvance(Consumer<? super E> action) {
  1111. if (action == null)
  1112. throw new NullPointerException();
  1113. int hi = getFence(), i = index;
  1114. if (i < hi) {
  1115. index = i + 1;
  1116. @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
  1117. action.accept(e);
  1118. if (list.modCount != expectedModCount)
  1119. throw new ConcurrentModificationException();
  1120. return true;
  1121. }
  1122. return false;
  1123. }
  1124. public void forEachRemaining(Consumer<? super E> action) {
  1125. int i, hi, mc; // hoist accesses and checks from loop
  1126. ArrayList<E> lst; Object[] a;
  1127. if (action == null)
  1128. throw new NullPointerException();
  1129. if ((lst = list) != null && (a = lst.elementData) != null) {
  1130. if ((hi = fence) < 0) {
  1131. mc = lst.modCount;
  1132. hi = lst.size;
  1133. }
  1134. else
  1135. mc = expectedModCount;
  1136. if ((i = index) >= 0 && (index = hi) <= a.length) {
  1137. for (; i < hi; ++i) {
  1138. @SuppressWarnings("unchecked") E e = (E) a[i];
  1139. action.accept(e);
  1140. }
  1141. if (lst.modCount == mc)
  1142. return;
  1143. }
  1144. }
  1145. throw new ConcurrentModificationException();
  1146. }
  1147. public long estimateSize() {
  1148. return (long) (getFence() - index);
  1149. }
  1150. public int characteristics() {
  1151. return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
  1152. }
  1153. }
  1154. @Override
  1155. public boolean removeIf(Predicate<? super E> filter) {
  1156. Objects.requireNonNull(filter);
  1157. // figure out which elements are to be removed
  1158. // any exception thrown from the filter predicate at this stage
  1159. // will leave the collection unmodified
  1160. int removeCount = 0;
  1161. final BitSet removeSet = new BitSet(size);
  1162. final int expectedModCount = modCount;
  1163. final int size = this.size;
  1164. for (int i=0; modCount == expectedModCount && i < size; i++) {
  1165. @SuppressWarnings("unchecked")
  1166. final E element = (E) elementData[i];
  1167. if (filter.test(element)) {
  1168. removeSet.set(i);
  1169. removeCount++;
  1170. }
  1171. }
  1172. if (modCount != expectedModCount) {
  1173. throw new ConcurrentModificationException();
  1174. }
  1175. // shift surviving elements left over the spaces left by removed elements
  1176. final boolean anyToRemove = removeCount > 0;
  1177. if (anyToRemove) {
  1178. final int newSize = size - removeCount;
  1179. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
  1180. i = removeSet.nextClearBit(i);
  1181. elementData[j] = elementData[i];
  1182. }
  1183. for (int k=newSize; k < size; k++) {
  1184. elementData[k] = null; // Let gc do its work
  1185. }
  1186. this.size = newSize;
  1187. if (modCount != expectedModCount) {
  1188. throw new ConcurrentModificationException();
  1189. }
  1190. modCount++;
  1191. }
  1192. return anyToRemove;
  1193. }
  1194. @Override
  1195. @SuppressWarnings("unchecked")
  1196. public void replaceAll(UnaryOperator<E> operator) {
  1197. Objects.requireNonNull(operator);
  1198. final int expectedModCount = modCount;
  1199. final int size = this.size;
  1200. for (int i=0; modCount == expectedModCount && i < size; i++) {
  1201. elementData[i] = operator.apply((E) elementData[i]);
  1202. }
  1203. if (modCount != expectedModCount) {
  1204. throw new ConcurrentModificationException();
  1205. }
  1206. modCount++;
  1207. }
  1208. @Override
  1209. @SuppressWarnings("unchecked")
  1210. public void sort(Comparator<? super E> c) {
  1211. final int expectedModCount = modCount;
  1212. Arrays.sort((E[]) elementData, 0, size, c);
  1213. if (modCount != expectedModCount) {
  1214. throw new ConcurrentModificationException();
  1215. }
  1216. modCount++;
  1217. }

}

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  3. {

从以上源码

1.我们发现在进行扩容的时候,每次扩容都是在原来的基础上扩大原来的1.5倍;
2.在进行扩容的时候都要进行复制数组,在进行复制数组的时候是用的是System.arraycopy(elementData, 0, a, 0, size);我们知道每次的搬运数组都会浪费大量的时间,所以要减少复制数组的行为;
3.我们看到ArrayList默认的数组元素是10个,因此我们在创建数组的时候要注意了;
4.ArrayList底层是用动态数组实现的;
5.它继承了一些类,实现了一些接口,实现的接口中有一个RandomAccess
这个是随机访问的接口,所以在对Arraylist用下标的方式快很多,
6.我们在对其进行修改的时候用ArrayList也是比较快的。
7.这个ArrayList只适合单线程,多线程用Vector。

发表评论

表情:
评论列表 (有 0 条评论,524人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ArrayList分析

    ArrayList是一种最常用的集合类,底层数据结构是数组,提供动态扩展数组长度的特性,允许元素的值为null。ArrayList是一种非线程安全的集合类,若要在多线程的环境,

    相关 ArrayList分析

    构造函数(有参和无参): 无参:有个被transient关键字修饰的elementData的Object类型长度为0的数组。 有参:参数的含义就是这个集合的含量,在Arra