ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/AbstractList.java
Revision: 1.18
Committed: Tue Sep 11 15:24:16 2007 UTC (16 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.17: +135 -241 lines
Log Message:
4802633: (coll) AbstractList.addAll(-1,emptyCollection) doesn't throw IndexOutOfBoundsException
6359979: (coll) Speed up collection iteration
6533203: (coll) AbstractList.ListItr.add might corrupt iterator state if enclosing add throws
6533307: (coll) Optimize AbstractList range checking

File Contents

# User Rev Content
1 dl 1.1 /*
2 jsr166 1.18 * Copyright 1997-2007 Sun Microsystems, Inc. All Rights Reserved.
3 jsr166 1.17 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 dl 1.1 *
5 jsr166 1.17 * This code is free software; you can redistribute it and/or modify it
6     * under the terms of the GNU General Public License version 2 only, as
7     * published by the Free Software Foundation. Sun designates this
8     * particular file as subject to the "Classpath" exception as provided
9     * by Sun in the LICENSE file that accompanied this code.
10     *
11     * This code is distributed in the hope that it will be useful, but WITHOUT
12     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13     * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14     * version 2 for more details (a copy is included in the LICENSE file that
15     * accompanied this code).
16     *
17     * You should have received a copy of the GNU General Public License version
18     * 2 along with this work; if not, write to the Free Software Foundation,
19     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20     *
21     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22     * CA 95054 USA or visit www.sun.com if you need additional information or
23     * have any questions.
24 dl 1.1 */
25    
26     package java.util;
27    
28     /**
29 jsr166 1.13 * This class provides a skeletal implementation of the {@link List}
30 dl 1.1 * interface to minimize the effort required to implement this interface
31     * backed by a "random access" data store (such as an array). For sequential
32 jsr166 1.13 * access data (such as a linked list), {@link AbstractSequentialList} should
33 jsr166 1.12 * be used in preference to this class.
34 dl 1.1 *
35 jsr166 1.13 * <p>To implement an unmodifiable list, the programmer needs only to extend
36     * this class and provide implementations for the {@link #get(int)} and
37     * {@link List#size() size()} methods.
38 dl 1.1 *
39 jsr166 1.13 * <p>To implement a modifiable list, the programmer must additionally
40     * override the {@link #set(int, Object) set(int, E)} method (which otherwise
41     * throws an {@code UnsupportedOperationException}). If the list is
42     * variable-size the programmer must additionally override the
43     * {@link #add(int, Object) add(int, E)} and {@link #remove(int)} methods.
44 dl 1.1 *
45 jsr166 1.12 * <p>The programmer should generally provide a void (no argument) and collection
46 jsr166 1.13 * constructor, as per the recommendation in the {@link Collection} interface
47 jsr166 1.12 * specification.
48 dl 1.1 *
49 jsr166 1.12 * <p>Unlike the other abstract collection implementations, the programmer does
50 dl 1.1 * <i>not</i> have to provide an iterator implementation; the iterator and
51     * list iterator are implemented by this class, on top of the "random access"
52 jsr166 1.13 * methods:
53     * {@link #get(int)},
54     * {@link #set(int, Object) set(int, E)},
55     * {@link #add(int, Object) add(int, E)} and
56     * {@link #remove(int)}.
57 dl 1.1 *
58 jsr166 1.13 * <p>The documentation for each non-abstract method in this class describes its
59 dl 1.1 * implementation in detail. Each of these methods may be overridden if the
60 jsr166 1.12 * collection being implemented admits a more efficient implementation.
61 dl 1.1 *
62 jsr166 1.12 * <p>This class is a member of the
63 jsr166 1.11 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
64 dl 1.1 * Java Collections Framework</a>.
65     *
66     * @author Josh Bloch
67     * @author Neal Gafter
68 jsr166 1.7 * @version %I%, %G%
69 dl 1.1 * @since 1.2
70     */
71    
72     public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
73     /**
74     * Sole constructor. (For invocation by subclass constructors, typically
75     * implicit.)
76     */
77     protected AbstractList() {
78     }
79    
80     /**
81     * Appends the specified element to the end of this list (optional
82     * operation).
83     *
84     * <p>Lists that support this operation may place limitations on what
85     * elements may be added to this list. In particular, some
86     * lists will refuse to add null elements, and others will impose
87     * restrictions on the type of elements that may be added. List
88     * classes should clearly specify in their documentation any restrictions
89     * on what elements may be added.
90     *
91 jsr166 1.12 * <p>This implementation calls {@code add(size(), e)}.
92 dl 1.1 *
93     * <p>Note that this implementation throws an
94 jsr166 1.13 * {@code UnsupportedOperationException} unless
95     * {@link #add(int, Object) add(int, E)} is overridden.
96 dl 1.1 *
97     * @param e element to be appended to this list
98 jsr166 1.12 * @return {@code true} (as specified by {@link Collection#add})
99     * @throws UnsupportedOperationException if the {@code add} operation
100 dl 1.1 * is not supported by this list
101     * @throws ClassCastException if the class of the specified element
102     * prevents it from being added to this list
103     * @throws NullPointerException if the specified element is null and this
104     * list does not permit null elements
105     * @throws IllegalArgumentException if some property of this element
106     * prevents it from being added to this list
107     */
108     public boolean add(E e) {
109     add(size(), e);
110     return true;
111     }
112    
113     /**
114     * {@inheritDoc}
115     *
116     * @throws IndexOutOfBoundsException {@inheritDoc}
117     */
118     abstract public E get(int index);
119    
120     /**
121     * {@inheritDoc}
122     *
123     * <p>This implementation always throws an
124 jsr166 1.12 * {@code UnsupportedOperationException}.
125 dl 1.1 *
126     * @throws UnsupportedOperationException {@inheritDoc}
127     * @throws ClassCastException {@inheritDoc}
128     * @throws NullPointerException {@inheritDoc}
129     * @throws IllegalArgumentException {@inheritDoc}
130     * @throws IndexOutOfBoundsException {@inheritDoc}
131     */
132     public E set(int index, E element) {
133     throw new UnsupportedOperationException();
134     }
135    
136     /**
137     * {@inheritDoc}
138     *
139     * <p>This implementation always throws an
140 jsr166 1.12 * {@code UnsupportedOperationException}.
141 dl 1.1 *
142     * @throws UnsupportedOperationException {@inheritDoc}
143     * @throws ClassCastException {@inheritDoc}
144     * @throws NullPointerException {@inheritDoc}
145     * @throws IllegalArgumentException {@inheritDoc}
146     * @throws IndexOutOfBoundsException {@inheritDoc}
147     */
148     public void add(int index, E element) {
149     throw new UnsupportedOperationException();
150     }
151    
152     /**
153     * {@inheritDoc}
154     *
155     * <p>This implementation always throws an
156 jsr166 1.12 * {@code UnsupportedOperationException}.
157 dl 1.1 *
158     * @throws UnsupportedOperationException {@inheritDoc}
159     * @throws IndexOutOfBoundsException {@inheritDoc}
160     */
161     public E remove(int index) {
162     throw new UnsupportedOperationException();
163     }
164    
165    
166     // Search Operations
167    
168     /**
169     * {@inheritDoc}
170     *
171     * <p>This implementation first gets a list iterator (with
172 jsr166 1.12 * {@code listIterator()}). Then, it iterates over the list until the
173 dl 1.1 * specified element is found or the end of the list is reached.
174     *
175     * @throws ClassCastException {@inheritDoc}
176     * @throws NullPointerException {@inheritDoc}
177     */
178     public int indexOf(Object o) {
179     ListIterator<E> e = listIterator();
180     if (o==null) {
181     while (e.hasNext())
182     if (e.next()==null)
183     return e.previousIndex();
184     } else {
185     while (e.hasNext())
186     if (o.equals(e.next()))
187     return e.previousIndex();
188     }
189     return -1;
190     }
191    
192     /**
193     * {@inheritDoc}
194     *
195     * <p>This implementation first gets a list iterator that points to the end
196 jsr166 1.12 * of the list (with {@code listIterator(size())}). Then, it iterates
197 dl 1.1 * backwards over the list until the specified element is found, or the
198     * beginning of the list is reached.
199     *
200     * @throws ClassCastException {@inheritDoc}
201     * @throws NullPointerException {@inheritDoc}
202     */
203     public int lastIndexOf(Object o) {
204     ListIterator<E> e = listIterator(size());
205     if (o==null) {
206     while (e.hasPrevious())
207     if (e.previous()==null)
208     return e.nextIndex();
209     } else {
210     while (e.hasPrevious())
211     if (o.equals(e.previous()))
212     return e.nextIndex();
213     }
214     return -1;
215     }
216    
217    
218     // Bulk Operations
219    
220     /**
221     * Removes all of the elements from this list (optional operation).
222     * The list will be empty after this call returns.
223     *
224 jsr166 1.12 * <p>This implementation calls {@code removeRange(0, size())}.
225 dl 1.1 *
226     * <p>Note that this implementation throws an
227 jsr166 1.12 * {@code UnsupportedOperationException} unless {@code remove(int
228     * index)} or {@code removeRange(int fromIndex, int toIndex)} is
229 dl 1.1 * overridden.
230     *
231 jsr166 1.12 * @throws UnsupportedOperationException if the {@code clear} operation
232 dl 1.1 * is not supported by this list
233     */
234     public void clear() {
235     removeRange(0, size());
236     }
237    
238     /**
239     * {@inheritDoc}
240     *
241 jsr166 1.13 * <p>This implementation gets an iterator over the specified collection
242     * and iterates over it, inserting the elements obtained from the
243     * iterator into this list at the appropriate position, one at a time,
244     * using {@code add(int, E)}.
245     * Many implementations will override this method for efficiency.
246 dl 1.1 *
247     * <p>Note that this implementation throws an
248 jsr166 1.13 * {@code UnsupportedOperationException} unless
249     * {@link #add(int, Object) add(int, E)} is overridden.
250 dl 1.1 *
251     * @throws UnsupportedOperationException {@inheritDoc}
252     * @throws ClassCastException {@inheritDoc}
253     * @throws NullPointerException {@inheritDoc}
254     * @throws IllegalArgumentException {@inheritDoc}
255     * @throws IndexOutOfBoundsException {@inheritDoc}
256     */
257     public boolean addAll(int index, Collection<? extends E> c) {
258 jsr166 1.18 rangeCheckForAdd(index);
259 dl 1.1 boolean modified = false;
260     Iterator<? extends E> e = c.iterator();
261     while (e.hasNext()) {
262     add(index++, e.next());
263     modified = true;
264     }
265     return modified;
266     }
267    
268    
269     // Iterators
270    
271     /**
272 jsr166 1.14 * Returns an iterator over the elements in this list in proper sequence.
273 dl 1.1 *
274 jsr166 1.13 * <p>This implementation returns a straightforward implementation of the
275 jsr166 1.12 * iterator interface, relying on the backing list's {@code size()},
276 jsr166 1.13 * {@code get(int)}, and {@code remove(int)} methods.
277 dl 1.1 *
278 jsr166 1.13 * <p>Note that the iterator returned by this method will throw an
279 jsr166 1.18 * {@link UnsupportedOperationException} in response to its
280 jsr166 1.12 * {@code remove} method unless the list's {@code remove(int)} method is
281 jsr166 1.13 * overridden.
282 dl 1.1 *
283 jsr166 1.13 * <p>This implementation can be made to throw runtime exceptions in the
284     * face of concurrent modification, as described in the specification
285 jsr166 1.18 * for the (protected) {@link #modCount} field.
286 dl 1.1 *
287     * @return an iterator over the elements in this list in proper sequence
288     */
289     public Iterator<E> iterator() {
290     return new Itr();
291     }
292    
293     /**
294     * {@inheritDoc}
295     *
296 jsr166 1.12 * <p>This implementation returns {@code listIterator(0)}.
297 dl 1.1 *
298     * @see #listIterator(int)
299     */
300     public ListIterator<E> listIterator() {
301     return listIterator(0);
302     }
303    
304     /**
305     * {@inheritDoc}
306     *
307     * <p>This implementation returns a straightforward implementation of the
308 jsr166 1.12 * {@code ListIterator} interface that extends the implementation of the
309     * {@code Iterator} interface returned by the {@code iterator()} method.
310     * The {@code ListIterator} implementation relies on the backing list's
311 jsr166 1.14 * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
312 jsr166 1.12 * and {@code remove(int)} methods.
313 dl 1.1 *
314     * <p>Note that the list iterator returned by this implementation will
315 jsr166 1.18 * throw an {@link UnsupportedOperationException} in response to its
316 jsr166 1.12 * {@code remove}, {@code set} and {@code add} methods unless the
317 jsr166 1.13 * list's {@code remove(int)}, {@code set(int, E)}, and
318     * {@code add(int, E)} methods are overridden.
319 dl 1.1 *
320     * <p>This implementation can be made to throw runtime exceptions in the
321     * face of concurrent modification, as described in the specification for
322 jsr166 1.18 * the (protected) {@link #modCount} field.
323 dl 1.1 *
324     * @throws IndexOutOfBoundsException {@inheritDoc}
325     */
326     public ListIterator<E> listIterator(final int index) {
327 jsr166 1.18 rangeCheckForAdd(index);
328 dl 1.1
329     return new ListItr(index);
330     }
331    
332     private class Itr implements Iterator<E> {
333     /**
334     * Index of element to be returned by subsequent call to next.
335     */
336     int cursor = 0;
337    
338     /**
339     * Index of element returned by most recent call to next or
340     * previous. Reset to -1 if this element is deleted by a call
341     * to remove.
342     */
343     int lastRet = -1;
344    
345     /**
346     * The modCount value that the iterator believes that the backing
347     * List should have. If this expectation is violated, the iterator
348     * has detected concurrent modification.
349     */
350     int expectedModCount = modCount;
351    
352 dl 1.4 public boolean hasNext() {
353     return cursor != size();
354 dl 1.1 }
355    
356 dl 1.4 public E next() {
357 dl 1.8 checkForComodification();
358     try {
359 jsr166 1.18 int i = cursor;
360     E next = get(i);
361     lastRet = i;
362     cursor = i + 1;
363 dl 1.8 return next;
364     } catch (IndexOutOfBoundsException e) {
365     checkForComodification();
366     throw new NoSuchElementException();
367     }
368 dl 1.1 }
369    
370 dl 1.4 public void remove() {
371 jsr166 1.18 if (lastRet < 0)
372 dl 1.1 throw new IllegalStateException();
373 dl 1.8 checkForComodification();
374    
375 dl 1.1 try {
376     AbstractList.this.remove(lastRet);
377     if (lastRet < cursor)
378     cursor--;
379     lastRet = -1;
380     expectedModCount = modCount;
381     } catch (IndexOutOfBoundsException e) {
382     throw new ConcurrentModificationException();
383     }
384     }
385 dl 1.8
386     final void checkForComodification() {
387     if (modCount != expectedModCount)
388     throw new ConcurrentModificationException();
389     }
390 dl 1.1 }
391 jsr166 1.6
392 dl 1.4 private class ListItr extends Itr implements ListIterator<E> {
393 dl 1.1 ListItr(int index) {
394     cursor = index;
395     }
396    
397     public boolean hasPrevious() {
398 dl 1.4 return cursor != 0;
399 dl 1.1 }
400    
401 dl 1.8 public E previous() {
402     checkForComodification();
403     try {
404     int i = cursor - 1;
405     E previous = get(i);
406     lastRet = cursor = i;
407     return previous;
408     } catch (IndexOutOfBoundsException e) {
409     checkForComodification();
410     throw new NoSuchElementException();
411     }
412     }
413    
414 dl 1.1 public int nextIndex() {
415     return cursor;
416     }
417    
418     public int previousIndex() {
419 dl 1.8 return cursor-1;
420 dl 1.1 }
421    
422     public void set(E e) {
423 jsr166 1.18 if (lastRet < 0)
424 dl 1.1 throw new IllegalStateException();
425 dl 1.8 checkForComodification();
426    
427 dl 1.1 try {
428     AbstractList.this.set(lastRet, e);
429     expectedModCount = modCount;
430     } catch (IndexOutOfBoundsException ex) {
431     throw new ConcurrentModificationException();
432     }
433     }
434    
435     public void add(E e) {
436 dl 1.8 checkForComodification();
437    
438 dl 1.1 try {
439 jsr166 1.18 int i = cursor;
440 dl 1.1 AbstractList.this.add(i, e);
441     lastRet = -1;
442 jsr166 1.18 cursor = i + 1;
443 dl 1.1 expectedModCount = modCount;
444     } catch (IndexOutOfBoundsException ex) {
445     throw new ConcurrentModificationException();
446     }
447     }
448     }
449    
450     /**
451     * {@inheritDoc}
452     *
453     * <p>This implementation returns a list that subclasses
454 jsr166 1.12 * {@code AbstractList}. The subclass stores, in private fields, the
455 dl 1.1 * offset of the subList within the backing list, the size of the subList
456     * (which can change over its lifetime), and the expected
457 jsr166 1.12 * {@code modCount} value of the backing list. There are two variants
458     * of the subclass, one of which implements {@code RandomAccess}.
459     * If this list implements {@code RandomAccess} the returned list will
460     * be an instance of the subclass that implements {@code RandomAccess}.
461     *
462 jsr166 1.14 * <p>The subclass's {@code set(int, E)}, {@code get(int)},
463     * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
464 jsr166 1.12 * Collection)} and {@code removeRange(int, int)} methods all
465 dl 1.1 * delegate to the corresponding methods on the backing abstract list,
466     * after bounds-checking the index and adjusting for the offset. The
467 jsr166 1.12 * {@code addAll(Collection c)} method merely returns {@code addAll(size,
468     * c)}.
469 dl 1.1 *
470 jsr166 1.12 * <p>The {@code listIterator(int)} method returns a "wrapper object"
471 dl 1.1 * over a list iterator on the backing list, which is created with the
472 jsr166 1.12 * corresponding method on the backing list. The {@code iterator} method
473     * merely returns {@code listIterator()}, and the {@code size} method
474     * merely returns the subclass's {@code size} field.
475 dl 1.1 *
476 jsr166 1.12 * <p>All methods first check to see if the actual {@code modCount} of
477 dl 1.1 * the backing list is equal to its expected value, and throw a
478 jsr166 1.12 * {@code ConcurrentModificationException} if it is not.
479 dl 1.1 *
480 jsr166 1.18 * @throws IndexOutOfBoundsException if an endpoint index value is out of range
481 jsr166 1.14 * {@code (fromIndex < 0 || toIndex > size)}
482 dl 1.1 * @throws IllegalArgumentException if the endpoint indices are out of order
483 jsr166 1.14 * {@code (fromIndex > toIndex)}
484 dl 1.1 */
485     public List<E> subList(int fromIndex, int toIndex) {
486     return (this instanceof RandomAccess ?
487 jsr166 1.18 new RandomAccessSubList<E>(this, fromIndex, toIndex) :
488     new SubList<E>(this, fromIndex, toIndex));
489 dl 1.1 }
490    
491     // Comparison and hashing
492    
493     /**
494     * Compares the specified object with this list for equality. Returns
495 jsr166 1.12 * {@code true} if and only if the specified object is also a list, both
496 dl 1.1 * lists have the same size, and all corresponding pairs of elements in
497 jsr166 1.12 * the two lists are <i>equal</i>. (Two elements {@code e1} and
498     * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null :
499     * e1.equals(e2))}.) In other words, two lists are defined to be
500 jsr166 1.18 * equal if they contain the same elements in the same order.<p>
501 dl 1.1 *
502 jsr166 1.18 * This implementation first checks if the specified object is this
503 jsr166 1.12 * list. If so, it returns {@code true}; if not, it checks if the
504     * specified object is a list. If not, it returns {@code false}; if so,
505 dl 1.1 * it iterates over both lists, comparing corresponding pairs of elements.
506 jsr166 1.12 * If any comparison returns {@code false}, this method returns
507     * {@code false}. If either iterator runs out of elements before the
508     * other it returns {@code false} (as the lists are of unequal length);
509     * otherwise it returns {@code true} when the iterations complete.
510 dl 1.1 *
511     * @param o the object to be compared for equality with this list
512 jsr166 1.12 * @return {@code true} if the specified object is equal to this list
513 dl 1.1 */
514     public boolean equals(Object o) {
515     if (o == this)
516     return true;
517     if (!(o instanceof List))
518     return false;
519    
520     ListIterator<E> e1 = listIterator();
521     ListIterator e2 = ((List) o).listIterator();
522     while(e1.hasNext() && e2.hasNext()) {
523     E o1 = e1.next();
524     Object o2 = e2.next();
525     if (!(o1==null ? o2==null : o1.equals(o2)))
526     return false;
527     }
528     return !(e1.hasNext() || e2.hasNext());
529     }
530    
531     /**
532 jsr166 1.13 * Returns the hash code value for this list.
533 dl 1.1 *
534 jsr166 1.13 * <p>This implementation uses exactly the code that is used to define the
535 dl 1.1 * list hash function in the documentation for the {@link List#hashCode}
536     * method.
537     *
538     * @return the hash code value for this list
539     */
540     public int hashCode() {
541     int hashCode = 1;
542 jsr166 1.18 for (E e : this)
543     hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
544 dl 1.1 return hashCode;
545     }
546    
547     /**
548     * Removes from this list all of the elements whose index is between
549 jsr166 1.12 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
550 dl 1.1 * Shifts any succeeding elements to the left (reduces their index).
551 jsr166 1.18 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
552     * (If {@code toIndex==fromIndex}, this operation has no effect.)
553 dl 1.1 *
554 jsr166 1.13 * <p>This method is called by the {@code clear} operation on this list
555 dl 1.1 * and its subLists. Overriding this method to take advantage of
556     * the internals of the list implementation can <i>substantially</i>
557 jsr166 1.12 * improve the performance of the {@code clear} operation on this list
558 jsr166 1.13 * and its subLists.
559 dl 1.1 *
560 jsr166 1.13 * <p>This implementation gets a list iterator positioned before
561 jsr166 1.12 * {@code fromIndex}, and repeatedly calls {@code ListIterator.next}
562     * followed by {@code ListIterator.remove} until the entire range has
563     * been removed. <b>Note: if {@code ListIterator.remove} requires linear
564 dl 1.1 * time, this implementation requires quadratic time.</b>
565     *
566     * @param fromIndex index of first element to be removed
567     * @param toIndex index after last element to be removed
568     */
569     protected void removeRange(int fromIndex, int toIndex) {
570     ListIterator<E> it = listIterator(fromIndex);
571     for (int i=0, n=toIndex-fromIndex; i<n; i++) {
572     it.next();
573     it.remove();
574     }
575     }
576    
577     /**
578     * The number of times this list has been <i>structurally modified</i>.
579     * Structural modifications are those that change the size of the
580     * list, or otherwise perturb it in such a fashion that iterations in
581 jsr166 1.13 * progress may yield incorrect results.
582 dl 1.1 *
583 jsr166 1.13 * <p>This field is used by the iterator and list iterator implementation
584 jsr166 1.12 * returned by the {@code iterator} and {@code listIterator} methods.
585 dl 1.1 * If the value of this field changes unexpectedly, the iterator (or list
586 jsr166 1.12 * iterator) will throw a {@code ConcurrentModificationException} in
587     * response to the {@code next}, {@code remove}, {@code previous},
588     * {@code set} or {@code add} operations. This provides
589 dl 1.1 * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
590 jsr166 1.13 * the face of concurrent modification during iteration.
591 dl 1.1 *
592 jsr166 1.13 * <p><b>Use of this field by subclasses is optional.</b> If a subclass
593 dl 1.1 * wishes to provide fail-fast iterators (and list iterators), then it
594 jsr166 1.14 * merely has to increment this field in its {@code add(int, E)} and
595 jsr166 1.12 * {@code remove(int)} methods (and any other methods that it overrides
596 dl 1.1 * that result in structural modifications to the list). A single call to
597 jsr166 1.14 * {@code add(int, E)} or {@code remove(int)} must add no more than
598 dl 1.1 * one to this field, or the iterators (and list iterators) will throw
599 jsr166 1.12 * bogus {@code ConcurrentModificationExceptions}. If an implementation
600 dl 1.1 * does not wish to provide fail-fast iterators, this field may be
601     * ignored.
602     */
603     protected transient int modCount = 0;
604 jsr166 1.18
605     private void rangeCheckForAdd(int index) {
606     if (index < 0 || index > size())
607     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
608     }
609    
610     private String outOfBoundsMsg(int index) {
611     return "Index: "+index+", Size: "+size();
612     }
613 dl 1.1 }
614    
615     class SubList<E> extends AbstractList<E> {
616 jsr166 1.18 private final AbstractList<E> l;
617     private final int offset;
618     private int size;
619    
620     SubList(AbstractList<E> list, int fromIndex, int toIndex) {
621 dl 1.1 if (fromIndex < 0)
622     throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
623 jsr166 1.18 if (toIndex > list.size())
624 dl 1.1 throw new IndexOutOfBoundsException("toIndex = " + toIndex);
625     if (fromIndex > toIndex)
626     throw new IllegalArgumentException("fromIndex(" + fromIndex +
627     ") > toIndex(" + toIndex + ")");
628 jsr166 1.18 l = list;
629     offset = fromIndex;
630     size = toIndex - fromIndex;
631     this.modCount = l.modCount;
632 dl 1.1 }
633    
634     public E set(int index, E element) {
635 jsr166 1.18 rangeCheck(index);
636     checkForComodification();
637     return l.set(index+offset, element);
638 dl 1.1 }
639    
640     public E get(int index) {
641 jsr166 1.18 rangeCheck(index);
642     checkForComodification();
643     return l.get(index+offset);
644 dl 1.1 }
645    
646     public int size() {
647 jsr166 1.18 checkForComodification();
648     return size;
649 dl 1.1 }
650    
651     public void add(int index, E element) {
652 jsr166 1.18 rangeCheckForAdd(index);
653     checkForComodification();
654     l.add(index+offset, element);
655     this.modCount = l.modCount;
656     size++;
657 dl 1.1 }
658    
659     public E remove(int index) {
660 jsr166 1.18 rangeCheck(index);
661     checkForComodification();
662     E result = l.remove(index+offset);
663     this.modCount = l.modCount;
664     size--;
665 dl 1.1 return result;
666     }
667    
668     protected void removeRange(int fromIndex, int toIndex) {
669 jsr166 1.18 checkForComodification();
670     l.removeRange(fromIndex+offset, toIndex+offset);
671     this.modCount = l.modCount;
672     size -= (toIndex-fromIndex);
673 dl 1.1 }
674    
675     public boolean addAll(Collection<? extends E> c) {
676 jsr166 1.18 return addAll(size, c);
677 dl 1.1 }
678    
679     public boolean addAll(int index, Collection<? extends E> c) {
680 jsr166 1.18 rangeCheckForAdd(index);
681 dl 1.1 int cSize = c.size();
682     if (cSize==0)
683     return false;
684    
685 jsr166 1.18 checkForComodification();
686     l.addAll(offset+index, c);
687     this.modCount = l.modCount;
688     size += cSize;
689 dl 1.1 return true;
690     }
691    
692     public Iterator<E> iterator() {
693 jsr166 1.18 return listIterator();
694 dl 1.8 }
695    
696 jsr166 1.18 public ListIterator<E> listIterator(final int index) {
697     checkForComodification();
698     rangeCheckForAdd(index);
699 dl 1.1
700 jsr166 1.18 return new ListIterator<E>() {
701     private final ListIterator<E> i = l.listIterator(index+offset);
702 dl 1.1
703 jsr166 1.18 public boolean hasNext() {
704     return nextIndex() < size;
705     }
706 dl 1.1
707 jsr166 1.18 public E next() {
708     if (hasNext())
709     return i.next();
710     else
711     throw new NoSuchElementException();
712     }
713 dl 1.1
714 jsr166 1.18 public boolean hasPrevious() {
715     return previousIndex() >= 0;
716     }
717 dl 1.1
718 jsr166 1.18 public E previous() {
719     if (hasPrevious())
720     return i.previous();
721     else
722     throw new NoSuchElementException();
723     }
724 dl 1.1
725 jsr166 1.18 public int nextIndex() {
726     return i.nextIndex() - offset;
727     }
728 dl 1.1
729 jsr166 1.18 public int previousIndex() {
730     return i.previousIndex() - offset;
731 dl 1.1 }
732    
733 jsr166 1.18 public void remove() {
734     i.remove();
735     SubList.this.modCount = l.modCount;
736     size--;
737 dl 1.1 }
738    
739 jsr166 1.18 public void set(E e) {
740     i.set(e);
741 dl 1.1 }
742    
743 jsr166 1.18 public void add(E e) {
744     i.add(e);
745     SubList.this.modCount = l.modCount;
746     size++;
747 dl 1.1 }
748 jsr166 1.18 };
749     }
750    
751     public List<E> subList(int fromIndex, int toIndex) {
752     return new SubList<E>(this, fromIndex, toIndex);
753     }
754    
755     private void rangeCheck(int index) {
756     if (index < 0 || index >= size)
757     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
758     }
759    
760     private void rangeCheckForAdd(int index) {
761     if (index < 0 || index > size)
762     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
763     }
764 dl 1.1
765 jsr166 1.18 private String outOfBoundsMsg(int index) {
766     return "Index: "+index+", Size: "+size;
767 dl 1.1 }
768    
769 jsr166 1.18 private void checkForComodification() {
770     if (this.modCount != l.modCount)
771     throw new ConcurrentModificationException();
772     }
773 dl 1.1 }
774    
775     class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
776 jsr166 1.18 RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
777     super(list, fromIndex, toIndex);
778 dl 1.1 }
779    
780     public List<E> subList(int fromIndex, int toIndex) {
781 jsr166 1.18 return new RandomAccessSubList<E>(this, fromIndex, toIndex);
782 dl 1.1 }
783     }