ArrayList.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /* ArrayList.java -- JDK1.2's answer to Vector; this is an array-backed
  2. implementation of the List interface
  3. Copyright (C) 1998, 1999, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import java.io.IOException;
  34. import java.io.ObjectInputStream;
  35. import java.io.ObjectOutputStream;
  36. import java.io.Serializable;
  37. import java.lang.reflect.Array;
  38. /**
  39. * An array-backed implementation of the List interface. This implements
  40. * all optional list operations, and permits null elements, so that it is
  41. * better than Vector, which it replaces. Random access is roughly constant
  42. * time, and iteration is roughly linear time, so it is nice and fast, with
  43. * less overhead than a LinkedList.
  44. * <p>
  45. *
  46. * Each list has a capacity, and as the array reaches that capacity it
  47. * is automatically transferred to a larger array. You also have access to
  48. * ensureCapacity and trimToSize to control the backing array's size, avoiding
  49. * reallocation or wasted memory.
  50. * <p>
  51. *
  52. * ArrayList is not synchronized, so if you need multi-threaded access,
  53. * consider using:<br>
  54. * <code>List l = Collections.synchronizedList(new ArrayList(...));</code>
  55. * <p>
  56. *
  57. * The iterators are <i>fail-fast</i>, meaning that any structural
  58. * modification, except for <code>remove()</code> called on the iterator
  59. * itself, cause the iterator to throw a
  60. * {@link ConcurrentModificationException} rather than exhibit
  61. * non-deterministic behavior.
  62. *
  63. * @author Jon A. Zeppieri
  64. * @author Bryce McKinlay
  65. * @author Eric Blake (ebb9@email.byu.edu)
  66. * @see Collection
  67. * @see List
  68. * @see LinkedList
  69. * @see Vector
  70. * @see Collections#synchronizedList(List)
  71. * @see AbstractList
  72. * @status updated to 1.4
  73. */
  74. public class ArrayList<E> extends AbstractList<E>
  75. implements List<E>, RandomAccess, Cloneable, Serializable
  76. {
  77. /**
  78. * Compatible with JDK 1.2
  79. */
  80. private static final long serialVersionUID = 8683452581122892189L;
  81. /**
  82. * The default capacity for new ArrayLists.
  83. */
  84. private static final int DEFAULT_CAPACITY = 10;
  85. /**
  86. * The number of elements in this list.
  87. * @serial the list size
  88. */
  89. private int size;
  90. /**
  91. * Where the data is stored.
  92. */
  93. private transient E[] data;
  94. /**
  95. * Construct a new ArrayList with the supplied initial capacity.
  96. *
  97. * @param capacity initial capacity of this ArrayList
  98. * @throws IllegalArgumentException if capacity is negative
  99. */
  100. public ArrayList(int capacity)
  101. {
  102. // Must explicitly check, to get correct exception.
  103. if (capacity < 0)
  104. throw new IllegalArgumentException();
  105. data = (E[]) new Object[capacity];
  106. }
  107. /**
  108. * Construct a new ArrayList with the default capacity (16).
  109. */
  110. public ArrayList()
  111. {
  112. this(DEFAULT_CAPACITY);
  113. }
  114. /**
  115. * Construct a new ArrayList, and initialize it with the elements
  116. * in the supplied Collection. The initial capacity is 110% of the
  117. * Collection's size.
  118. *
  119. * @param c the collection whose elements will initialize this list
  120. * @throws NullPointerException if c is null
  121. */
  122. public ArrayList(Collection<? extends E> c)
  123. {
  124. this((int) (c.size() * 1.1f));
  125. addAll(c);
  126. }
  127. /**
  128. * Trims the capacity of this List to be equal to its size;
  129. * a memory saver.
  130. */
  131. public void trimToSize()
  132. {
  133. // Not a structural change from the perspective of iterators on this list,
  134. // so don't update modCount.
  135. if (size != data.length)
  136. {
  137. E[] newData = (E[]) new Object[size];
  138. System.arraycopy(data, 0, newData, 0, size);
  139. data = newData;
  140. }
  141. }
  142. /**
  143. * Guarantees that this list will have at least enough capacity to
  144. * hold minCapacity elements. This implementation will grow the list to
  145. * max(current * 2, minCapacity) if (minCapacity &gt; current). The JCL says
  146. * explictly that "this method increases its capacity to minCap", while
  147. * the JDK 1.3 online docs specify that the list will grow to at least the
  148. * size specified.
  149. *
  150. * @param minCapacity the minimum guaranteed capacity
  151. */
  152. public void ensureCapacity(int minCapacity)
  153. {
  154. int current = data.length;
  155. if (minCapacity > current)
  156. {
  157. E[] newData = (E[]) new Object[Math.max(current * 2, minCapacity)];
  158. System.arraycopy(data, 0, newData, 0, size);
  159. data = newData;
  160. }
  161. }
  162. /**
  163. * Returns the number of elements in this list.
  164. *
  165. * @return the list size
  166. */
  167. public int size()
  168. {
  169. return size;
  170. }
  171. /**
  172. * Checks if the list is empty.
  173. *
  174. * @return true if there are no elements
  175. */
  176. public boolean isEmpty()
  177. {
  178. return size == 0;
  179. }
  180. /**
  181. * Returns true iff element is in this ArrayList.
  182. *
  183. * @param e the element whose inclusion in the List is being tested
  184. * @return true if the list contains e
  185. */
  186. public boolean contains(Object e)
  187. {
  188. return indexOf(e) != -1;
  189. }
  190. /**
  191. * Returns the lowest index at which element appears in this List, or
  192. * -1 if it does not appear.
  193. *
  194. * @param e the element whose inclusion in the List is being tested
  195. * @return the index where e was found
  196. */
  197. public int indexOf(Object e)
  198. {
  199. for (int i = 0; i < size; i++)
  200. if (equals(e, data[i]))
  201. return i;
  202. return -1;
  203. }
  204. /**
  205. * Returns the highest index at which element appears in this List, or
  206. * -1 if it does not appear.
  207. *
  208. * @param e the element whose inclusion in the List is being tested
  209. * @return the index where e was found
  210. */
  211. public int lastIndexOf(Object e)
  212. {
  213. for (int i = size - 1; i >= 0; i--)
  214. if (equals(e, data[i]))
  215. return i;
  216. return -1;
  217. }
  218. /**
  219. * Creates a shallow copy of this ArrayList (elements are not cloned).
  220. *
  221. * @return the cloned object
  222. */
  223. public Object clone()
  224. {
  225. ArrayList<E> clone = null;
  226. try
  227. {
  228. clone = (ArrayList<E>) super.clone();
  229. clone.data = (E[]) data.clone();
  230. }
  231. catch (CloneNotSupportedException e)
  232. {
  233. // Impossible to get here.
  234. }
  235. return clone;
  236. }
  237. /**
  238. * Returns an Object array containing all of the elements in this ArrayList.
  239. * The array is independent of this list.
  240. *
  241. * @return an array representation of this list
  242. */
  243. public Object[] toArray()
  244. {
  245. E[] array = (E[]) new Object[size];
  246. System.arraycopy(data, 0, array, 0, size);
  247. return array;
  248. }
  249. /**
  250. * Returns an Array whose component type is the runtime component type of
  251. * the passed-in Array. The returned Array is populated with all of the
  252. * elements in this ArrayList. If the passed-in Array is not large enough
  253. * to store all of the elements in this List, a new Array will be created
  254. * and returned; if the passed-in Array is <i>larger</i> than the size
  255. * of this List, then size() index will be set to null.
  256. *
  257. * @param a the passed-in Array
  258. * @return an array representation of this list
  259. * @throws ArrayStoreException if the runtime type of a does not allow
  260. * an element in this list
  261. * @throws NullPointerException if a is null
  262. */
  263. public <T> T[] toArray(T[] a)
  264. {
  265. if (a.length < size)
  266. a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
  267. else if (a.length > size)
  268. a[size] = null;
  269. System.arraycopy(data, 0, a, 0, size);
  270. return a;
  271. }
  272. /**
  273. * Retrieves the element at the user-supplied index.
  274. *
  275. * @param index the index of the element we are fetching
  276. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  277. */
  278. public E get(int index)
  279. {
  280. checkBoundExclusive(index);
  281. return data[index];
  282. }
  283. /**
  284. * Sets the element at the specified index. The new element, e,
  285. * can be an object of any type or null.
  286. *
  287. * @param index the index at which the element is being set
  288. * @param e the element to be set
  289. * @return the element previously at the specified index
  290. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= 0
  291. */
  292. public E set(int index, E e)
  293. {
  294. checkBoundExclusive(index);
  295. E result = data[index];
  296. data[index] = e;
  297. return result;
  298. }
  299. /**
  300. * Appends the supplied element to the end of this list.
  301. * The element, e, can be an object of any type or null.
  302. *
  303. * @param e the element to be appended to this list
  304. * @return true, the add will always succeed
  305. */
  306. public boolean add(E e)
  307. {
  308. modCount++;
  309. if (size == data.length)
  310. ensureCapacity(size + 1);
  311. data[size++] = e;
  312. return true;
  313. }
  314. /**
  315. * Adds the supplied element at the specified index, shifting all
  316. * elements currently at that index or higher one to the right.
  317. * The element, e, can be an object of any type or null.
  318. *
  319. * @param index the index at which the element is being added
  320. * @param e the item being added
  321. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
  322. */
  323. public void add(int index, E e)
  324. {
  325. checkBoundInclusive(index);
  326. modCount++;
  327. if (size == data.length)
  328. ensureCapacity(size + 1);
  329. if (index != size)
  330. System.arraycopy(data, index, data, index + 1, size - index);
  331. data[index] = e;
  332. size++;
  333. }
  334. /**
  335. * Removes the element at the user-supplied index.
  336. *
  337. * @param index the index of the element to be removed
  338. * @return the removed Object
  339. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt;= size()
  340. */
  341. public E remove(int index)
  342. {
  343. checkBoundExclusive(index);
  344. E r = data[index];
  345. modCount++;
  346. if (index != --size)
  347. System.arraycopy(data, index + 1, data, index, size - index);
  348. // Aid for garbage collection by releasing this pointer.
  349. data[size] = null;
  350. return r;
  351. }
  352. /**
  353. * Removes all elements from this List
  354. */
  355. public void clear()
  356. {
  357. if (size > 0)
  358. {
  359. modCount++;
  360. // Allow for garbage collection.
  361. Arrays.fill(data, 0, size, null);
  362. size = 0;
  363. }
  364. }
  365. /**
  366. * Add each element in the supplied Collection to this List. It is undefined
  367. * what happens if you modify the list while this is taking place; for
  368. * example, if the collection contains this list. c can contain objects
  369. * of any type, as well as null values.
  370. *
  371. * @param c a Collection containing elements to be added to this List
  372. * @return true if the list was modified, in other words c is not empty
  373. * @throws NullPointerException if c is null
  374. */
  375. public boolean addAll(Collection<? extends E> c)
  376. {
  377. return addAll(size, c);
  378. }
  379. /**
  380. * Add all elements in the supplied collection, inserting them beginning
  381. * at the specified index. c can contain objects of any type, as well
  382. * as null values.
  383. *
  384. * @param index the index at which the elements will be inserted
  385. * @param c the Collection containing the elements to be inserted
  386. * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; 0
  387. * @throws NullPointerException if c is null
  388. */
  389. public boolean addAll(int index, Collection<? extends E> c)
  390. {
  391. checkBoundInclusive(index);
  392. Iterator<? extends E> itr = c.iterator();
  393. int csize = c.size();
  394. modCount++;
  395. if (csize + size > data.length)
  396. ensureCapacity(size + csize);
  397. int end = index + csize;
  398. if (size > 0 && index != size)
  399. System.arraycopy(data, index, data, end, size - index);
  400. size += csize;
  401. for ( ; index < end; index++)
  402. data[index] = itr.next();
  403. return csize > 0;
  404. }
  405. /**
  406. * Removes all elements in the half-open interval [fromIndex, toIndex).
  407. * Does nothing when toIndex is equal to fromIndex.
  408. *
  409. * @param fromIndex the first index which will be removed
  410. * @param toIndex one greater than the last index which will be removed
  411. * @throws IndexOutOfBoundsException if fromIndex &gt; toIndex
  412. */
  413. protected void removeRange(int fromIndex, int toIndex)
  414. {
  415. int change = toIndex - fromIndex;
  416. if (change > 0)
  417. {
  418. modCount++;
  419. System.arraycopy(data, toIndex, data, fromIndex, size - toIndex);
  420. size -= change;
  421. }
  422. else if (change < 0)
  423. throw new IndexOutOfBoundsException();
  424. }
  425. /**
  426. * Checks that the index is in the range of possible elements (inclusive).
  427. *
  428. * @param index the index to check
  429. * @throws IndexOutOfBoundsException if index &gt; size
  430. */
  431. private void checkBoundInclusive(int index)
  432. {
  433. // Implementation note: we do not check for negative ranges here, since
  434. // use of a negative index will cause an ArrayIndexOutOfBoundsException,
  435. // a subclass of the required exception, with no effort on our part.
  436. if (index > size)
  437. raiseBoundsError(index);
  438. }
  439. /**
  440. * Checks that the index is in the range of existing elements (exclusive).
  441. *
  442. * @param index the index to check
  443. * @throws IndexOutOfBoundsException if index &gt;= size
  444. */
  445. private void checkBoundExclusive(int index)
  446. {
  447. // Implementation note: we do not check for negative ranges here, since
  448. // use of a negative index will cause an ArrayIndexOutOfBoundsException,
  449. // a subclass of the required exception, with no effort on our part.
  450. if (index >= size)
  451. raiseBoundsError(index);
  452. }
  453. /**
  454. * Raise the ArrayIndexOfOutBoundsException.
  455. *
  456. * @param index the index of the access
  457. * @throws IndexOutOfBoundsException unconditionally
  458. */
  459. private void raiseBoundsError(int index)
  460. {
  461. // Implementaion note: put in a separate method to make the JITs job easier
  462. // (separate common from uncommon code at method boundaries when trivial to
  463. // do so).
  464. throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
  465. }
  466. /**
  467. * Remove from this list all elements contained in the given collection.
  468. * This is not public, due to Sun's API, but this performs in linear
  469. * time while the default behavior of AbstractList would be quadratic.
  470. *
  471. * @param c the collection to filter out
  472. * @return true if this list changed
  473. * @throws NullPointerException if c is null
  474. */
  475. boolean removeAllInternal(Collection<?> c)
  476. {
  477. int i;
  478. int j;
  479. for (i = 0; i < size; i++)
  480. if (c.contains(data[i]))
  481. break;
  482. if (i == size)
  483. return false;
  484. modCount++;
  485. for (j = i++; i < size; i++)
  486. if (! c.contains(data[i]))
  487. data[j++] = data[i];
  488. size -= i - j;
  489. return true;
  490. }
  491. /**
  492. * Retain in this vector only the elements contained in the given collection.
  493. * This is not public, due to Sun's API, but this performs in linear
  494. * time while the default behavior of AbstractList would be quadratic.
  495. *
  496. * @param c the collection to filter by
  497. * @return true if this vector changed
  498. * @throws NullPointerException if c is null
  499. * @since 1.2
  500. */
  501. boolean retainAllInternal(Collection<?> c)
  502. {
  503. int i;
  504. int j;
  505. for (i = 0; i < size; i++)
  506. if (! c.contains(data[i]))
  507. break;
  508. if (i == size)
  509. return false;
  510. modCount++;
  511. for (j = i++; i < size; i++)
  512. if (c.contains(data[i]))
  513. data[j++] = data[i];
  514. size -= i - j;
  515. return true;
  516. }
  517. /**
  518. * Serializes this object to the given stream.
  519. *
  520. * @param s the stream to write to
  521. * @throws IOException if the underlying stream fails
  522. * @serialData the size field (int), the length of the backing array
  523. * (int), followed by its elements (Objects) in proper order.
  524. */
  525. private void writeObject(ObjectOutputStream s) throws IOException
  526. {
  527. // The 'size' field.
  528. s.defaultWriteObject();
  529. // We serialize unused list entries to preserve capacity.
  530. int len = data.length;
  531. s.writeInt(len);
  532. // it would be more efficient to just write "size" items,
  533. // this need readObject read "size" items too.
  534. for (int i = 0; i < size; i++)
  535. s.writeObject(data[i]);
  536. }
  537. /**
  538. * Deserializes this object from the given stream.
  539. *
  540. * @param s the stream to read from
  541. * @throws ClassNotFoundException if the underlying stream fails
  542. * @throws IOException if the underlying stream fails
  543. * @serialData the size field (int), the length of the backing array
  544. * (int), followed by its elements (Objects) in proper order.
  545. */
  546. private void readObject(ObjectInputStream s)
  547. throws IOException, ClassNotFoundException
  548. {
  549. // the `size' field.
  550. s.defaultReadObject();
  551. int capacity = s.readInt();
  552. data = (E[]) new Object[capacity];
  553. for (int i = 0; i < size; i++)
  554. data[i] = (E) s.readObject();
  555. }
  556. }