Print this page
Split |
Close |
Expand all |
Collapse all |
--- old/src/share/classes/java/util/ArrayList.java
+++ new/src/share/classes/java/util/ArrayList.java
1 1 /*
2 2 * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
3 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 4 *
5 5 * This code is free software; you can redistribute it and/or modify it
6 6 * under the terms of the GNU General Public License version 2 only, as
7 7 * published by the Free Software Foundation. Oracle designates this
8 8 * particular file as subject to the "Classpath" exception as provided
9 9 * by Oracle in the LICENSE file that accompanied this code.
10 10 *
11 11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 14 * version 2 for more details (a copy is included in the LICENSE file that
15 15 * accompanied this code).
16 16 *
17 17 * You should have received a copy of the GNU General Public License version
18 18 * 2 along with this work; if not, write to the Free Software Foundation,
19 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 20 *
21 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 22 * or visit www.oracle.com if you need additional information or have any
23 23 * questions.
24 24 */
25 25
26 26 package java.util;
27 27
28 28 /**
29 29 * Resizable-array implementation of the <tt>List</tt> interface. Implements
30 30 * all optional list operations, and permits all elements, including
31 31 * <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,
32 32 * this class provides methods to manipulate the size of the array that is
33 33 * used internally to store the list. (This class is roughly equivalent to
34 34 * <tt>Vector</tt>, except that it is unsynchronized.)
35 35 *
36 36 * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
37 37 * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
38 38 * time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,
39 39 * that is, adding n elements requires O(n) time. All of the other operations
40 40 * run in linear time (roughly speaking). The constant factor is low compared
41 41 * to that for the <tt>LinkedList</tt> implementation.
42 42 *
43 43 * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is
44 44 * the size of the array used to store the elements in the list. It is always
45 45 * at least as large as the list size. As elements are added to an ArrayList,
46 46 * its capacity grows automatically. The details of the growth policy are not
47 47 * specified beyond the fact that adding an element has constant amortized
48 48 * time cost.
49 49 *
50 50 * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance
51 51 * before adding a large number of elements using the <tt>ensureCapacity</tt>
52 52 * operation. This may reduce the amount of incremental reallocation.
53 53 *
54 54 * <p><strong>Note that this implementation is not synchronized.</strong>
55 55 * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
56 56 * and at least one of the threads modifies the list structurally, it
57 57 * <i>must</i> be synchronized externally. (A structural modification is
58 58 * any operation that adds or deletes one or more elements, or explicitly
59 59 * resizes the backing array; merely setting the value of an element is not
60 60 * a structural modification.) This is typically accomplished by
61 61 * synchronizing on some object that naturally encapsulates the list.
62 62 *
63 63 * If no such object exists, the list should be "wrapped" using the
64 64 * {@link Collections#synchronizedList Collections.synchronizedList}
65 65 * method. This is best done at creation time, to prevent accidental
66 66 * unsynchronized access to the list:<pre>
67 67 * List list = Collections.synchronizedList(new ArrayList(...));</pre>
68 68 *
69 69 * <p><a name="fail-fast"/>
70 70 * The iterators returned by this class's {@link #iterator() iterator} and
71 71 * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
72 72 * if the list is structurally modified at any time after the iterator is
73 73 * created, in any way except through the iterator's own
74 74 * {@link ListIterator#remove() remove} or
75 75 * {@link ListIterator#add(Object) add} methods, the iterator will throw a
76 76 * {@link ConcurrentModificationException}. Thus, in the face of
77 77 * concurrent modification, the iterator fails quickly and cleanly, rather
78 78 * than risking arbitrary, non-deterministic behavior at an undetermined
79 79 * time in the future.
80 80 *
81 81 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
82 82 * as it is, generally speaking, impossible to make any hard guarantees in the
83 83 * presence of unsynchronized concurrent modification. Fail-fast iterators
84 84 * throw {@code ConcurrentModificationException} on a best-effort basis.
85 85 * Therefore, it would be wrong to write a program that depended on this
86 86 * exception for its correctness: <i>the fail-fast behavior of iterators
87 87 * should be used only to detect bugs.</i>
88 88 *
89 89 * <p>This class is a member of the
90 90 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
91 91 * Java Collections Framework</a>.
92 92 *
93 93 * @author Josh Bloch
94 94 * @author Neal Gafter
95 95 * @see Collection
96 96 * @see List
97 97 * @see LinkedList
98 98 * @see Vector
99 99 * @since 1.2
100 100 */
101 101
102 102 public class ArrayList<E> extends AbstractList<E>
103 103 implements List<E>, RandomAccess, Cloneable, java.io.Serializable
104 104 {
105 105 private static final long serialVersionUID = 8683452581122892189L;
106 106
107 107 /**
108 108 * The array buffer into which the elements of the ArrayList are stored.
109 109 * The capacity of the ArrayList is the length of this array buffer.
110 110 */
111 111 private transient Object[] elementData;
112 112
↓ open down ↓ |
112 lines elided |
↑ open up ↑ |
113 113 /**
114 114 * The size of the ArrayList (the number of elements it contains).
115 115 *
116 116 * @serial
117 117 */
118 118 private int size;
119 119
120 120 /**
121 121 * Constructs an empty list with the specified initial capacity.
122 122 *
123 - * @param initialCapacity the initial capacity of the list
124 - * @exception IllegalArgumentException if the specified initial capacity
125 - * is negative
123 + * @param initialCapacity the initial capacity of the list
124 + * @throws IllegalArgumentException if the specified initial capacity
125 + * is negative
126 126 */
127 127 public ArrayList(int initialCapacity) {
128 128 super();
129 129 if (initialCapacity < 0)
130 130 throw new IllegalArgumentException("Illegal Capacity: "+
131 131 initialCapacity);
132 132 this.elementData = new Object[initialCapacity];
133 133 }
134 134
135 135 /**
136 136 * Constructs an empty list with an initial capacity of ten.
137 137 */
138 138 public ArrayList() {
139 139 this(10);
140 140 }
141 141
142 142 /**
143 143 * Constructs a list containing the elements of the specified
144 144 * collection, in the order they are returned by the collection's
145 145 * iterator.
146 146 *
147 147 * @param c the collection whose elements are to be placed into this list
148 148 * @throws NullPointerException if the specified collection is null
149 149 */
150 150 public ArrayList(Collection<? extends E> c) {
151 151 elementData = c.toArray();
152 152 size = elementData.length;
153 153 // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 154 if (elementData.getClass() != Object[].class)
155 155 elementData = Arrays.copyOf(elementData, size, Object[].class);
156 156 }
157 157
158 158 /**
159 159 * Trims the capacity of this <tt>ArrayList</tt> instance to be the
160 160 * list's current size. An application can use this operation to minimize
161 161 * the storage of an <tt>ArrayList</tt> instance.
162 162 */
163 163 public void trimToSize() {
164 164 modCount++;
165 165 int oldCapacity = elementData.length;
↓ open down ↓ |
30 lines elided |
↑ open up ↑ |
166 166 if (size < oldCapacity) {
167 167 elementData = Arrays.copyOf(elementData, size);
168 168 }
169 169 }
170 170
171 171 /**
172 172 * Increases the capacity of this <tt>ArrayList</tt> instance, if
173 173 * necessary, to ensure that it can hold at least the number of elements
174 174 * specified by the minimum capacity argument.
175 175 *
176 - * @param minCapacity the desired minimum capacity
176 + * @param minCapacity the desired minimum capacity
177 177 */
178 178 public void ensureCapacity(int minCapacity) {
179 179 if (minCapacity > 0)
180 180 ensureCapacityInternal(minCapacity);
181 181 }
182 182
183 183 private void ensureCapacityInternal(int minCapacity) {
184 184 modCount++;
185 185 // overflow-conscious code
186 186 if (minCapacity - elementData.length > 0)
187 187 grow(minCapacity);
188 188 }
189 189
190 190 /**
191 191 * The maximum size of array to allocate.
192 192 * Some VMs reserve some header words in an array.
193 193 * Attempts to allocate larger arrays may result in
194 194 * OutOfMemoryError: Requested array size exceeds VM limit
195 195 */
196 196 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
197 197
198 198 /**
199 199 * Increases the capacity to ensure that it can hold at least the
200 200 * number of elements specified by the minimum capacity argument.
201 201 *
202 202 * @param minCapacity the desired minimum capacity
203 203 */
↓ open down ↓ |
17 lines elided |
↑ open up ↑ |
204 204 private void grow(int minCapacity) {
205 205 // overflow-conscious code
206 206 int oldCapacity = elementData.length;
207 207 int newCapacity = oldCapacity + (oldCapacity >> 1);
208 208 if (newCapacity - minCapacity < 0)
209 209 newCapacity = minCapacity;
210 210 if (newCapacity - MAX_ARRAY_SIZE > 0)
211 211 newCapacity = hugeCapacity(minCapacity);
212 212 // minCapacity is usually close to size, so this is a win:
213 213 elementData = Arrays.copyOf(elementData, newCapacity);
214 - }
214 + }
215 215
216 216 private static int hugeCapacity(int minCapacity) {
217 217 if (minCapacity < 0) // overflow
218 218 throw new OutOfMemoryError();
219 219 return (minCapacity > MAX_ARRAY_SIZE) ?
220 220 Integer.MAX_VALUE :
221 221 MAX_ARRAY_SIZE;
222 222 }
223 223
224 224 /**
225 225 * Returns the number of elements in this list.
226 226 *
227 227 * @return the number of elements in this list
228 228 */
229 229 public int size() {
230 230 return size;
231 231 }
232 232
233 233 /**
234 234 * Returns <tt>true</tt> if this list contains no elements.
235 235 *
236 236 * @return <tt>true</tt> if this list contains no elements
237 237 */
238 238 public boolean isEmpty() {
239 239 return size == 0;
240 240 }
241 241
242 242 /**
243 243 * Returns <tt>true</tt> if this list contains the specified element.
244 244 * More formally, returns <tt>true</tt> if and only if this list contains
245 245 * at least one element <tt>e</tt> such that
246 246 * <tt>(o==null ? e==null : o.equals(e))</tt>.
247 247 *
248 248 * @param o element whose presence in this list is to be tested
249 249 * @return <tt>true</tt> if this list contains the specified element
250 250 */
251 251 public boolean contains(Object o) {
252 252 return indexOf(o) >= 0;
253 253 }
254 254
255 255 /**
256 256 * Returns the index of the first occurrence of the specified element
257 257 * in this list, or -1 if this list does not contain the element.
258 258 * More formally, returns the lowest index <tt>i</tt> such that
259 259 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
260 260 * or -1 if there is no such index.
261 261 */
262 262 public int indexOf(Object o) {
263 263 if (o == null) {
264 264 for (int i = 0; i < size; i++)
265 265 if (elementData[i]==null)
266 266 return i;
267 267 } else {
268 268 for (int i = 0; i < size; i++)
269 269 if (o.equals(elementData[i]))
270 270 return i;
271 271 }
272 272 return -1;
273 273 }
274 274
275 275 /**
276 276 * Returns the index of the last occurrence of the specified element
277 277 * in this list, or -1 if this list does not contain the element.
278 278 * More formally, returns the highest index <tt>i</tt> such that
279 279 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
280 280 * or -1 if there is no such index.
281 281 */
282 282 public int lastIndexOf(Object o) {
283 283 if (o == null) {
284 284 for (int i = size-1; i >= 0; i--)
285 285 if (elementData[i]==null)
286 286 return i;
287 287 } else {
288 288 for (int i = size-1; i >= 0; i--)
289 289 if (o.equals(elementData[i]))
290 290 return i;
291 291 }
292 292 return -1;
293 293 }
294 294
295 295 /**
296 296 * Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
297 297 * elements themselves are not copied.)
298 298 *
299 299 * @return a clone of this <tt>ArrayList</tt> instance
300 300 */
301 301 public Object clone() {
302 302 try {
303 303 @SuppressWarnings("unchecked")
304 304 ArrayList<E> v = (ArrayList<E>) super.clone();
305 305 v.elementData = Arrays.copyOf(elementData, size);
306 306 v.modCount = 0;
307 307 return v;
308 308 } catch (CloneNotSupportedException e) {
309 309 // this shouldn't happen, since we are Cloneable
310 310 throw new InternalError();
311 311 }
312 312 }
313 313
314 314 /**
315 315 * Returns an array containing all of the elements in this list
316 316 * in proper sequence (from first to last element).
317 317 *
318 318 * <p>The returned array will be "safe" in that no references to it are
319 319 * maintained by this list. (In other words, this method must allocate
320 320 * a new array). The caller is thus free to modify the returned array.
321 321 *
322 322 * <p>This method acts as bridge between array-based and collection-based
323 323 * APIs.
324 324 *
325 325 * @return an array containing all of the elements in this list in
326 326 * proper sequence
327 327 */
328 328 public Object[] toArray() {
329 329 return Arrays.copyOf(elementData, size);
330 330 }
331 331
332 332 /**
333 333 * Returns an array containing all of the elements in this list in proper
334 334 * sequence (from first to last element); the runtime type of the returned
335 335 * array is that of the specified array. If the list fits in the
336 336 * specified array, it is returned therein. Otherwise, a new array is
337 337 * allocated with the runtime type of the specified array and the size of
338 338 * this list.
339 339 *
340 340 * <p>If the list fits in the specified array with room to spare
341 341 * (i.e., the array has more elements than the list), the element in
342 342 * the array immediately following the end of the collection is set to
343 343 * <tt>null</tt>. (This is useful in determining the length of the
344 344 * list <i>only</i> if the caller knows that the list does not contain
345 345 * any null elements.)
346 346 *
347 347 * @param a the array into which the elements of the list are to
348 348 * be stored, if it is big enough; otherwise, a new array of the
349 349 * same runtime type is allocated for this purpose.
350 350 * @return an array containing the elements of the list
351 351 * @throws ArrayStoreException if the runtime type of the specified array
352 352 * is not a supertype of the runtime type of every element in
353 353 * this list
354 354 * @throws NullPointerException if the specified array is null
355 355 */
356 356 @SuppressWarnings("unchecked")
357 357 public <T> T[] toArray(T[] a) {
358 358 if (a.length < size)
359 359 // Make a new array of a's runtime type, but my contents:
360 360 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
361 361 System.arraycopy(elementData, 0, a, 0, size);
362 362 if (a.length > size)
363 363 a[size] = null;
364 364 return a;
365 365 }
366 366
367 367 // Positional Access Operations
368 368
369 369 @SuppressWarnings("unchecked")
370 370 E elementData(int index) {
371 371 return (E) elementData[index];
372 372 }
373 373
374 374 /**
375 375 * Returns the element at the specified position in this list.
376 376 *
377 377 * @param index index of the element to return
378 378 * @return the element at the specified position in this list
379 379 * @throws IndexOutOfBoundsException {@inheritDoc}
380 380 */
381 381 public E get(int index) {
382 382 rangeCheck(index);
383 383
384 384 return elementData(index);
385 385 }
386 386
387 387 /**
388 388 * Replaces the element at the specified position in this list with
389 389 * the specified element.
390 390 *
391 391 * @param index index of the element to replace
392 392 * @param element element to be stored at the specified position
393 393 * @return the element previously at the specified position
394 394 * @throws IndexOutOfBoundsException {@inheritDoc}
395 395 */
396 396 public E set(int index, E element) {
397 397 rangeCheck(index);
398 398
399 399 E oldValue = elementData(index);
400 400 elementData[index] = element;
401 401 return oldValue;
402 402 }
403 403
404 404 /**
405 405 * Appends the specified element to the end of this list.
406 406 *
407 407 * @param e element to be appended to this list
408 408 * @return <tt>true</tt> (as specified by {@link Collection#add})
409 409 */
410 410 public boolean add(E e) {
411 411 ensureCapacityInternal(size + 1); // Increments modCount!!
412 412 elementData[size++] = e;
413 413 return true;
414 414 }
415 415
416 416 /**
417 417 * Inserts the specified element at the specified position in this
418 418 * list. Shifts the element currently at that position (if any) and
419 419 * any subsequent elements to the right (adds one to their indices).
420 420 *
421 421 * @param index index at which the specified element is to be inserted
422 422 * @param element element to be inserted
423 423 * @throws IndexOutOfBoundsException {@inheritDoc}
424 424 */
425 425 public void add(int index, E element) {
426 426 rangeCheckForAdd(index);
427 427
428 428 ensureCapacityInternal(size + 1); // Increments modCount!!
429 429 System.arraycopy(elementData, index, elementData, index + 1,
430 430 size - index);
431 431 elementData[index] = element;
432 432 size++;
433 433 }
434 434
435 435 /**
436 436 * Removes the element at the specified position in this list.
437 437 * Shifts any subsequent elements to the left (subtracts one from their
438 438 * indices).
439 439 *
440 440 * @param index the index of the element to be removed
441 441 * @return the element that was removed from the list
442 442 * @throws IndexOutOfBoundsException {@inheritDoc}
443 443 */
444 444 public E remove(int index) {
445 445 rangeCheck(index);
446 446
447 447 modCount++;
448 448 E oldValue = elementData(index);
449 449
450 450 int numMoved = size - index - 1;
451 451 if (numMoved > 0)
452 452 System.arraycopy(elementData, index+1, elementData, index,
453 453 numMoved);
454 454 elementData[--size] = null; // Let gc do its work
455 455
456 456 return oldValue;
457 457 }
458 458
459 459 /**
460 460 * Removes the first occurrence of the specified element from this list,
461 461 * if it is present. If the list does not contain the element, it is
462 462 * unchanged. More formally, removes the element with the lowest index
463 463 * <tt>i</tt> such that
464 464 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
465 465 * (if such an element exists). Returns <tt>true</tt> if this list
466 466 * contained the specified element (or equivalently, if this list
467 467 * changed as a result of the call).
468 468 *
469 469 * @param o element to be removed from this list, if present
470 470 * @return <tt>true</tt> if this list contained the specified element
471 471 */
472 472 public boolean remove(Object o) {
473 473 if (o == null) {
474 474 for (int index = 0; index < size; index++)
475 475 if (elementData[index] == null) {
476 476 fastRemove(index);
477 477 return true;
478 478 }
479 479 } else {
480 480 for (int index = 0; index < size; index++)
481 481 if (o.equals(elementData[index])) {
482 482 fastRemove(index);
483 483 return true;
484 484 }
485 485 }
486 486 return false;
487 487 }
488 488
489 489 /*
490 490 * Private remove method that skips bounds checking and does not
491 491 * return the value removed.
492 492 */
493 493 private void fastRemove(int index) {
494 494 modCount++;
495 495 int numMoved = size - index - 1;
496 496 if (numMoved > 0)
497 497 System.arraycopy(elementData, index+1, elementData, index,
498 498 numMoved);
499 499 elementData[--size] = null; // Let gc do its work
500 500 }
501 501
502 502 /**
503 503 * Removes all of the elements from this list. The list will
504 504 * be empty after this call returns.
505 505 */
506 506 public void clear() {
507 507 modCount++;
508 508
509 509 // Let gc do its work
510 510 for (int i = 0; i < size; i++)
511 511 elementData[i] = null;
512 512
513 513 size = 0;
514 514 }
515 515
516 516 /**
517 517 * Appends all of the elements in the specified collection to the end of
518 518 * this list, in the order that they are returned by the
519 519 * specified collection's Iterator. The behavior of this operation is
520 520 * undefined if the specified collection is modified while the operation
521 521 * is in progress. (This implies that the behavior of this call is
522 522 * undefined if the specified collection is this list, and this
523 523 * list is nonempty.)
524 524 *
525 525 * @param c collection containing elements to be added to this list
526 526 * @return <tt>true</tt> if this list changed as a result of the call
527 527 * @throws NullPointerException if the specified collection is null
528 528 */
529 529 public boolean addAll(Collection<? extends E> c) {
530 530 Object[] a = c.toArray();
531 531 int numNew = a.length;
532 532 ensureCapacityInternal(size + numNew); // Increments modCount
533 533 System.arraycopy(a, 0, elementData, size, numNew);
534 534 size += numNew;
535 535 return numNew != 0;
536 536 }
537 537
538 538 /**
539 539 * Inserts all of the elements in the specified collection into this
540 540 * list, starting at the specified position. Shifts the element
541 541 * currently at that position (if any) and any subsequent elements to
542 542 * the right (increases their indices). The new elements will appear
543 543 * in the list in the order that they are returned by the
544 544 * specified collection's iterator.
545 545 *
546 546 * @param index index at which to insert the first element from the
547 547 * specified collection
548 548 * @param c collection containing elements to be added to this list
549 549 * @return <tt>true</tt> if this list changed as a result of the call
550 550 * @throws IndexOutOfBoundsException {@inheritDoc}
551 551 * @throws NullPointerException if the specified collection is null
552 552 */
553 553 public boolean addAll(int index, Collection<? extends E> c) {
554 554 rangeCheckForAdd(index);
555 555
556 556 Object[] a = c.toArray();
557 557 int numNew = a.length;
558 558 ensureCapacityInternal(size + numNew); // Increments modCount
559 559
560 560 int numMoved = size - index;
561 561 if (numMoved > 0)
562 562 System.arraycopy(elementData, index, elementData, index + numNew,
563 563 numMoved);
564 564
565 565 System.arraycopy(a, 0, elementData, index, numNew);
566 566 size += numNew;
567 567 return numNew != 0;
568 568 }
569 569
570 570 /**
571 571 * Removes from this list all of the elements whose index is between
572 572 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
573 573 * Shifts any succeeding elements to the left (reduces their index).
574 574 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
575 575 * (If {@code toIndex==fromIndex}, this operation has no effect.)
576 576 *
577 577 * @throws IndexOutOfBoundsException if {@code fromIndex} or
578 578 * {@code toIndex} is out of range
579 579 * ({@code fromIndex < 0 ||
580 580 * fromIndex >= size() ||
581 581 * toIndex > size() ||
582 582 * toIndex < fromIndex})
583 583 */
584 584 protected void removeRange(int fromIndex, int toIndex) {
585 585 modCount++;
586 586 int numMoved = size - toIndex;
587 587 System.arraycopy(elementData, toIndex, elementData, fromIndex,
588 588 numMoved);
589 589
590 590 // Let gc do its work
591 591 int newSize = size - (toIndex-fromIndex);
592 592 while (size != newSize)
593 593 elementData[--size] = null;
594 594 }
595 595
596 596 /**
597 597 * Checks if the given index is in range. If not, throws an appropriate
598 598 * runtime exception. This method does *not* check if the index is
599 599 * negative: It is always used immediately prior to an array access,
600 600 * which throws an ArrayIndexOutOfBoundsException if index is negative.
601 601 */
602 602 private void rangeCheck(int index) {
603 603 if (index >= size)
604 604 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
605 605 }
606 606
607 607 /**
608 608 * A version of rangeCheck used by add and addAll.
609 609 */
610 610 private void rangeCheckForAdd(int index) {
611 611 if (index > size || index < 0)
612 612 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
613 613 }
614 614
615 615 /**
616 616 * Constructs an IndexOutOfBoundsException detail message.
617 617 * Of the many possible refactorings of the error handling code,
618 618 * this "outlining" performs best with both server and client VMs.
619 619 */
620 620 private String outOfBoundsMsg(int index) {
621 621 return "Index: "+index+", Size: "+size;
622 622 }
623 623
624 624 /**
625 625 * Removes from this list all of its elements that are contained in the
626 626 * specified collection.
627 627 *
628 628 * @param c collection containing elements to be removed from this list
629 629 * @return {@code true} if this list changed as a result of the call
630 630 * @throws ClassCastException if the class of an element of this list
631 631 * is incompatible with the specified collection (optional)
632 632 * @throws NullPointerException if this list contains a null element and the
633 633 * specified collection does not permit null elements (optional),
634 634 * or if the specified collection is null
635 635 * @see Collection#contains(Object)
636 636 */
637 637 public boolean removeAll(Collection<?> c) {
638 638 return batchRemove(c, false);
639 639 }
640 640
641 641 /**
642 642 * Retains only the elements in this list that are contained in the
643 643 * specified collection. In other words, removes from this list all
644 644 * of its elements that are not contained in the specified collection.
645 645 *
646 646 * @param c collection containing elements to be retained in this list
647 647 * @return {@code true} if this list changed as a result of the call
648 648 * @throws ClassCastException if the class of an element of this list
649 649 * is incompatible with the specified collection (optional)
650 650 * @throws NullPointerException if this list contains a null element and the
651 651 * specified collection does not permit null elements (optional),
652 652 * or if the specified collection is null
653 653 * @see Collection#contains(Object)
654 654 */
655 655 public boolean retainAll(Collection<?> c) {
656 656 return batchRemove(c, true);
657 657 }
658 658
659 659 private boolean batchRemove(Collection<?> c, boolean complement) {
660 660 final Object[] elementData = this.elementData;
661 661 int r = 0, w = 0;
662 662 boolean modified = false;
663 663 try {
664 664 for (; r < size; r++)
665 665 if (c.contains(elementData[r]) == complement)
666 666 elementData[w++] = elementData[r];
667 667 } finally {
668 668 // Preserve behavioral compatibility with AbstractCollection,
669 669 // even if c.contains() throws.
670 670 if (r != size) {
671 671 System.arraycopy(elementData, r,
672 672 elementData, w,
673 673 size - r);
674 674 w += size - r;
675 675 }
676 676 if (w != size) {
677 677 for (int i = w; i < size; i++)
678 678 elementData[i] = null;
679 679 modCount += size - w;
680 680 size = w;
681 681 modified = true;
682 682 }
683 683 }
684 684 return modified;
685 685 }
686 686
687 687 /**
688 688 * Save the state of the <tt>ArrayList</tt> instance to a stream (that
689 689 * is, serialize it).
690 690 *
691 691 * @serialData The length of the array backing the <tt>ArrayList</tt>
692 692 * instance is emitted (int), followed by all of its elements
693 693 * (each an <tt>Object</tt>) in the proper order.
694 694 */
695 695 private void writeObject(java.io.ObjectOutputStream s)
696 696 throws java.io.IOException{
697 697 // Write out element count, and any hidden stuff
698 698 int expectedModCount = modCount;
699 699 s.defaultWriteObject();
700 700
701 701 // Write out array length
702 702 s.writeInt(elementData.length);
703 703
704 704 // Write out all elements in the proper order.
705 705 for (int i=0; i<size; i++)
706 706 s.writeObject(elementData[i]);
707 707
708 708 if (modCount != expectedModCount) {
709 709 throw new ConcurrentModificationException();
710 710 }
711 711
712 712 }
713 713
714 714 /**
715 715 * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
716 716 * deserialize it).
717 717 */
718 718 private void readObject(java.io.ObjectInputStream s)
719 719 throws java.io.IOException, ClassNotFoundException {
720 720 // Read in size, and any hidden stuff
721 721 s.defaultReadObject();
722 722
723 723 // Read in array length and allocate array
724 724 int arrayLength = s.readInt();
725 725 Object[] a = elementData = new Object[arrayLength];
726 726
727 727 // Read in all elements in the proper order.
728 728 for (int i=0; i<size; i++)
729 729 a[i] = s.readObject();
730 730 }
731 731
732 732 /**
733 733 * Returns a list iterator over the elements in this list (in proper
734 734 * sequence), starting at the specified position in the list.
735 735 * The specified index indicates the first element that would be
736 736 * returned by an initial call to {@link ListIterator#next next}.
737 737 * An initial call to {@link ListIterator#previous previous} would
738 738 * return the element with the specified index minus one.
739 739 *
740 740 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
741 741 *
742 742 * @throws IndexOutOfBoundsException {@inheritDoc}
743 743 */
744 744 public ListIterator<E> listIterator(int index) {
745 745 if (index < 0 || index > size)
746 746 throw new IndexOutOfBoundsException("Index: "+index);
747 747 return new ListItr(index);
748 748 }
749 749
750 750 /**
751 751 * Returns a list iterator over the elements in this list (in proper
752 752 * sequence).
753 753 *
754 754 * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
755 755 *
756 756 * @see #listIterator(int)
757 757 */
758 758 public ListIterator<E> listIterator() {
759 759 return new ListItr(0);
760 760 }
761 761
762 762 /**
763 763 * Returns an iterator over the elements in this list in proper sequence.
764 764 *
765 765 * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
766 766 *
767 767 * @return an iterator over the elements in this list in proper sequence
768 768 */
769 769 public Iterator<E> iterator() {
770 770 return new Itr();
771 771 }
772 772
773 773 /**
774 774 * An optimized version of AbstractList.Itr
775 775 */
776 776 private class Itr implements Iterator<E> {
777 777 int cursor; // index of next element to return
778 778 int lastRet = -1; // index of last element returned; -1 if no such
779 779 int expectedModCount = modCount;
780 780
781 781 public boolean hasNext() {
782 782 return cursor != size;
783 783 }
784 784
785 785 @SuppressWarnings("unchecked")
786 786 public E next() {
787 787 checkForComodification();
788 788 int i = cursor;
789 789 if (i >= size)
790 790 throw new NoSuchElementException();
791 791 Object[] elementData = ArrayList.this.elementData;
792 792 if (i >= elementData.length)
793 793 throw new ConcurrentModificationException();
794 794 cursor = i + 1;
795 795 return (E) elementData[lastRet = i];
796 796 }
797 797
798 798 public void remove() {
799 799 if (lastRet < 0)
800 800 throw new IllegalStateException();
801 801 checkForComodification();
802 802
803 803 try {
804 804 ArrayList.this.remove(lastRet);
805 805 cursor = lastRet;
806 806 lastRet = -1;
807 807 expectedModCount = modCount;
808 808 } catch (IndexOutOfBoundsException ex) {
809 809 throw new ConcurrentModificationException();
810 810 }
811 811 }
812 812
813 813 final void checkForComodification() {
814 814 if (modCount != expectedModCount)
815 815 throw new ConcurrentModificationException();
816 816 }
817 817 }
818 818
819 819 /**
820 820 * An optimized version of AbstractList.ListItr
821 821 */
822 822 private class ListItr extends Itr implements ListIterator<E> {
823 823 ListItr(int index) {
824 824 super();
825 825 cursor = index;
826 826 }
827 827
828 828 public boolean hasPrevious() {
829 829 return cursor != 0;
830 830 }
831 831
832 832 public int nextIndex() {
833 833 return cursor;
834 834 }
835 835
836 836 public int previousIndex() {
837 837 return cursor - 1;
838 838 }
839 839
840 840 @SuppressWarnings("unchecked")
841 841 public E previous() {
842 842 checkForComodification();
843 843 int i = cursor - 1;
844 844 if (i < 0)
845 845 throw new NoSuchElementException();
846 846 Object[] elementData = ArrayList.this.elementData;
847 847 if (i >= elementData.length)
848 848 throw new ConcurrentModificationException();
849 849 cursor = i;
850 850 return (E) elementData[lastRet = i];
851 851 }
852 852
853 853 public void set(E e) {
854 854 if (lastRet < 0)
855 855 throw new IllegalStateException();
856 856 checkForComodification();
857 857
858 858 try {
859 859 ArrayList.this.set(lastRet, e);
860 860 } catch (IndexOutOfBoundsException ex) {
861 861 throw new ConcurrentModificationException();
862 862 }
863 863 }
864 864
865 865 public void add(E e) {
866 866 checkForComodification();
867 867
868 868 try {
869 869 int i = cursor;
870 870 ArrayList.this.add(i, e);
871 871 cursor = i + 1;
872 872 lastRet = -1;
873 873 expectedModCount = modCount;
874 874 } catch (IndexOutOfBoundsException ex) {
875 875 throw new ConcurrentModificationException();
876 876 }
877 877 }
878 878 }
879 879
880 880 /**
881 881 * Returns a view of the portion of this list between the specified
882 882 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
883 883 * {@code fromIndex} and {@code toIndex} are equal, the returned list is
884 884 * empty.) The returned list is backed by this list, so non-structural
885 885 * changes in the returned list are reflected in this list, and vice-versa.
886 886 * The returned list supports all of the optional list operations.
887 887 *
888 888 * <p>This method eliminates the need for explicit range operations (of
889 889 * the sort that commonly exist for arrays). Any operation that expects
890 890 * a list can be used as a range operation by passing a subList view
891 891 * instead of a whole list. For example, the following idiom
892 892 * removes a range of elements from a list:
893 893 * <pre>
894 894 * list.subList(from, to).clear();
895 895 * </pre>
896 896 * Similar idioms may be constructed for {@link #indexOf(Object)} and
897 897 * {@link #lastIndexOf(Object)}, and all of the algorithms in the
898 898 * {@link Collections} class can be applied to a subList.
899 899 *
900 900 * <p>The semantics of the list returned by this method become undefined if
901 901 * the backing list (i.e., this list) is <i>structurally modified</i> in
902 902 * any way other than via the returned list. (Structural modifications are
903 903 * those that change the size of this list, or otherwise perturb it in such
904 904 * a fashion that iterations in progress may yield incorrect results.)
905 905 *
906 906 * @throws IndexOutOfBoundsException {@inheritDoc}
907 907 * @throws IllegalArgumentException {@inheritDoc}
908 908 */
909 909 public List<E> subList(int fromIndex, int toIndex) {
910 910 subListRangeCheck(fromIndex, toIndex, size);
911 911 return new SubList(this, 0, fromIndex, toIndex);
912 912 }
913 913
914 914 static void subListRangeCheck(int fromIndex, int toIndex, int size) {
915 915 if (fromIndex < 0)
916 916 throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
917 917 if (toIndex > size)
918 918 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
919 919 if (fromIndex > toIndex)
920 920 throw new IllegalArgumentException("fromIndex(" + fromIndex +
921 921 ") > toIndex(" + toIndex + ")");
922 922 }
923 923
924 924 private class SubList extends AbstractList<E> implements RandomAccess {
925 925 private final AbstractList<E> parent;
926 926 private final int parentOffset;
927 927 private final int offset;
928 928 int size;
929 929
930 930 SubList(AbstractList<E> parent,
931 931 int offset, int fromIndex, int toIndex) {
932 932 this.parent = parent;
933 933 this.parentOffset = fromIndex;
934 934 this.offset = offset + fromIndex;
935 935 this.size = toIndex - fromIndex;
936 936 this.modCount = ArrayList.this.modCount;
937 937 }
938 938
939 939 public E set(int index, E e) {
940 940 rangeCheck(index);
941 941 checkForComodification();
942 942 E oldValue = ArrayList.this.elementData(offset + index);
943 943 ArrayList.this.elementData[offset + index] = e;
944 944 return oldValue;
945 945 }
946 946
947 947 public E get(int index) {
948 948 rangeCheck(index);
949 949 checkForComodification();
950 950 return ArrayList.this.elementData(offset + index);
951 951 }
952 952
953 953 public int size() {
954 954 checkForComodification();
955 955 return this.size;
956 956 }
957 957
958 958 public void add(int index, E e) {
959 959 rangeCheckForAdd(index);
960 960 checkForComodification();
961 961 parent.add(parentOffset + index, e);
962 962 this.modCount = parent.modCount;
963 963 this.size++;
964 964 }
965 965
966 966 public E remove(int index) {
967 967 rangeCheck(index);
968 968 checkForComodification();
969 969 E result = parent.remove(parentOffset + index);
970 970 this.modCount = parent.modCount;
971 971 this.size--;
972 972 return result;
973 973 }
974 974
975 975 protected void removeRange(int fromIndex, int toIndex) {
976 976 checkForComodification();
977 977 parent.removeRange(parentOffset + fromIndex,
978 978 parentOffset + toIndex);
979 979 this.modCount = parent.modCount;
980 980 this.size -= toIndex - fromIndex;
981 981 }
982 982
983 983 public boolean addAll(Collection<? extends E> c) {
984 984 return addAll(this.size, c);
985 985 }
986 986
987 987 public boolean addAll(int index, Collection<? extends E> c) {
988 988 rangeCheckForAdd(index);
989 989 int cSize = c.size();
990 990 if (cSize==0)
991 991 return false;
992 992
993 993 checkForComodification();
994 994 parent.addAll(parentOffset + index, c);
995 995 this.modCount = parent.modCount;
996 996 this.size += cSize;
997 997 return true;
998 998 }
999 999
1000 1000 public Iterator<E> iterator() {
1001 1001 return listIterator();
1002 1002 }
1003 1003
1004 1004 public ListIterator<E> listIterator(final int index) {
1005 1005 checkForComodification();
1006 1006 rangeCheckForAdd(index);
1007 1007 final int offset = this.offset;
1008 1008
1009 1009 return new ListIterator<E>() {
1010 1010 int cursor = index;
1011 1011 int lastRet = -1;
1012 1012 int expectedModCount = ArrayList.this.modCount;
1013 1013
1014 1014 public boolean hasNext() {
1015 1015 return cursor != SubList.this.size;
1016 1016 }
1017 1017
1018 1018 @SuppressWarnings("unchecked")
1019 1019 public E next() {
1020 1020 checkForComodification();
1021 1021 int i = cursor;
1022 1022 if (i >= SubList.this.size)
1023 1023 throw new NoSuchElementException();
1024 1024 Object[] elementData = ArrayList.this.elementData;
1025 1025 if (offset + i >= elementData.length)
1026 1026 throw new ConcurrentModificationException();
1027 1027 cursor = i + 1;
1028 1028 return (E) elementData[offset + (lastRet = i)];
1029 1029 }
1030 1030
1031 1031 public boolean hasPrevious() {
1032 1032 return cursor != 0;
1033 1033 }
1034 1034
1035 1035 @SuppressWarnings("unchecked")
1036 1036 public E previous() {
1037 1037 checkForComodification();
1038 1038 int i = cursor - 1;
1039 1039 if (i < 0)
1040 1040 throw new NoSuchElementException();
1041 1041 Object[] elementData = ArrayList.this.elementData;
1042 1042 if (offset + i >= elementData.length)
1043 1043 throw new ConcurrentModificationException();
1044 1044 cursor = i;
1045 1045 return (E) elementData[offset + (lastRet = i)];
1046 1046 }
1047 1047
1048 1048 public int nextIndex() {
1049 1049 return cursor;
1050 1050 }
1051 1051
1052 1052 public int previousIndex() {
1053 1053 return cursor - 1;
1054 1054 }
1055 1055
1056 1056 public void remove() {
1057 1057 if (lastRet < 0)
1058 1058 throw new IllegalStateException();
1059 1059 checkForComodification();
1060 1060
1061 1061 try {
1062 1062 SubList.this.remove(lastRet);
1063 1063 cursor = lastRet;
1064 1064 lastRet = -1;
1065 1065 expectedModCount = ArrayList.this.modCount;
1066 1066 } catch (IndexOutOfBoundsException ex) {
1067 1067 throw new ConcurrentModificationException();
1068 1068 }
1069 1069 }
1070 1070
1071 1071 public void set(E e) {
1072 1072 if (lastRet < 0)
1073 1073 throw new IllegalStateException();
1074 1074 checkForComodification();
1075 1075
1076 1076 try {
1077 1077 ArrayList.this.set(offset + lastRet, e);
1078 1078 } catch (IndexOutOfBoundsException ex) {
1079 1079 throw new ConcurrentModificationException();
1080 1080 }
1081 1081 }
1082 1082
1083 1083 public void add(E e) {
1084 1084 checkForComodification();
1085 1085
1086 1086 try {
1087 1087 int i = cursor;
1088 1088 SubList.this.add(i, e);
1089 1089 cursor = i + 1;
1090 1090 lastRet = -1;
1091 1091 expectedModCount = ArrayList.this.modCount;
1092 1092 } catch (IndexOutOfBoundsException ex) {
1093 1093 throw new ConcurrentModificationException();
1094 1094 }
1095 1095 }
1096 1096
1097 1097 final void checkForComodification() {
1098 1098 if (expectedModCount != ArrayList.this.modCount)
1099 1099 throw new ConcurrentModificationException();
1100 1100 }
1101 1101 };
1102 1102 }
1103 1103
1104 1104 public List<E> subList(int fromIndex, int toIndex) {
1105 1105 subListRangeCheck(fromIndex, toIndex, size);
1106 1106 return new SubList(this, offset, fromIndex, toIndex);
1107 1107 }
1108 1108
1109 1109 private void rangeCheck(int index) {
1110 1110 if (index < 0 || index >= this.size)
1111 1111 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1112 1112 }
1113 1113
1114 1114 private void rangeCheckForAdd(int index) {
1115 1115 if (index < 0 || index > this.size)
1116 1116 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1117 1117 }
1118 1118
1119 1119 private String outOfBoundsMsg(int index) {
1120 1120 return "Index: "+index+", Size: "+this.size;
1121 1121 }
1122 1122
1123 1123 private void checkForComodification() {
1124 1124 if (ArrayList.this.modCount != this.modCount)
1125 1125 throw new ConcurrentModificationException();
1126 1126 }
1127 1127 }
1128 1128 }
↓ open down ↓ |
904 lines elided |
↑ open up ↑ |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX