ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/AbstractList.java
Revision: 1.12
Committed: Mon Jun 26 00:46:50 2006 UTC (17 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.11: +97 -97 lines
Log Message:
doc sync with mustang

File Contents

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