ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/AbstractList.java
(Generate patch)

Comparing jsr166/src/main/java/util/AbstractList.java (file contents):
Revision 1.12 by jsr166, Mon Jun 26 00:46:50 2006 UTC vs.
Revision 1.19 by jsr166, Sun May 18 23:47:55 2008 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * 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   */
25  
26   package java.util;
27  
28   /**
29 < * This class provides a skeletal implementation of the {@code List}
29 > * This class provides a skeletal implementation of the {@link List}
30   * 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 < * access data (such as a linked list), {@code AbstractSequentialList} should
32 > * access data (such as a linked list), {@link AbstractSequentialList} should
33   * be used in preference to this class.
34   *
35 < * <p>To implement an unmodifiable list, the programmer needs only to extend this
36 < * class and provide implementations for the {@code get(int index)} and
37 < * {@code size()} methods.
38 < *
39 < * <p>To implement a modifiable list, the programmer must additionally override
40 < * the {@code set(int index, Object element)} method (which otherwise throws
41 < * an {@code UnsupportedOperationException}.  If the list is variable-size
42 < * the programmer must additionally override the {@code add(int index, Object
43 < * element)} and {@code remove(int index)} methods.
35 > * <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 > *
39 > * <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   *
45   * <p>The programmer should generally provide a void (no argument) and collection
46 < * constructor, as per the recommendation in the {@code Collection} interface
46 > * constructor, as per the recommendation in the {@link Collection} interface
47   * specification.
48   *
49   * <p>Unlike the other abstract collection implementations, the programmer does
50   * <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 < * methods: {@code get(int index)}, {@code set(int index, E element)},
53 < * {@code add(int index, E element)} and {@code remove(int index)}.
52 > * 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   *
58 < * <p>The documentation for each non-abstract methods in this class describes its
58 > * <p>The documentation for each non-abstract method in this class describes its
59   * implementation in detail.  Each of these methods may be overridden if the
60   * collection being implemented admits a more efficient implementation.
61   *
# Line 45 | Line 66 | package java.util;
66   * @author  Josh Bloch
67   * @author  Neal Gafter
68   * @version %I%, %G%
48 * @see Collection
49 * @see List
50 * @see AbstractSequentialList
51 * @see AbstractCollection
69   * @since 1.2
70   */
71  
# Line 74 | Line 91 | public abstract class AbstractList<E> ex
91       * <p>This implementation calls {@code add(size(), e)}.
92       *
93       * <p>Note that this implementation throws an
94 <     * {@code UnsupportedOperationException} unless {@code add(int, Object)}
95 <     * is overridden.
94 >     * {@code UnsupportedOperationException} unless
95 >     * {@link #add(int, Object) add(int, E)} is overridden.
96       *
97       * @param e element to be appended to this list
98       * @return {@code true} (as specified by {@link Collection#add})
# Line 89 | Line 106 | public abstract class AbstractList<E> ex
106       *         prevents it from being added to this list
107       */
108      public boolean add(E e) {
109 <        add(size(), e);
110 <        return true;
109 >        add(size(), e);
110 >        return true;
111      }
112  
113      /**
# Line 113 | Line 130 | public abstract class AbstractList<E> ex
130       * @throws IndexOutOfBoundsException     {@inheritDoc}
131       */
132      public E set(int index, E element) {
133 <        throw new UnsupportedOperationException();
133 >        throw new UnsupportedOperationException();
134      }
135  
136      /**
# Line 129 | Line 146 | public abstract class AbstractList<E> ex
146       * @throws IndexOutOfBoundsException     {@inheritDoc}
147       */
148      public void add(int index, E element) {
149 <        throw new UnsupportedOperationException();
149 >        throw new UnsupportedOperationException();
150      }
151  
152      /**
# Line 142 | Line 159 | public abstract class AbstractList<E> ex
159       * @throws IndexOutOfBoundsException     {@inheritDoc}
160       */
161      public E remove(int index) {
162 <        throw new UnsupportedOperationException();
162 >        throw new UnsupportedOperationException();
163      }
164  
165  
# Line 159 | Line 176 | public abstract class AbstractList<E> ex
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;
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      /**
# Line 184 | Line 201 | public abstract class AbstractList<E> ex
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;
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  
# Line 221 | Line 238 | public abstract class AbstractList<E> ex
238      /**
239       * {@inheritDoc}
240       *
241 <     * <p>This implementation gets an iterator over the specified collection and
242 <     * iterates over it, inserting the elements obtained from the iterator
243 <     * into this list at the appropriate position, one at a time, using
244 <     * {@code add(int, Object)}.  Many implementations will override this
245 <     * method for efficiency.
241 >     * <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       *
247       * <p>Note that this implementation throws an
248 <     * {@code UnsupportedOperationException} unless {@code add(int, Object)}
249 <     * is overridden.
248 >     * {@code UnsupportedOperationException} unless
249 >     * {@link #add(int, Object) add(int, E)} is overridden.
250       *
251       * @throws UnsupportedOperationException {@inheritDoc}
252       * @throws ClassCastException            {@inheritDoc}
# Line 238 | Line 255 | public abstract class AbstractList<E> ex
255       * @throws IndexOutOfBoundsException     {@inheritDoc}
256       */
257      public boolean addAll(int index, Collection<? extends E> c) {
258 <        boolean modified = false;
259 <        Iterator<? extends E> e = c.iterator();
260 <        while (e.hasNext()) {
261 <            add(index++, e.next());
262 <            modified = true;
263 <        }
264 <        return modified;
258 >        rangeCheckForAdd(index);
259 >        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 <     * Returns an iterator over the elements in this list in proper
255 <     * sequence. <p>
272 >     * Returns an iterator over the elements in this list in proper sequence.
273       *
274 <     * This implementation returns a straightforward implementation of the
274 >     * <p>This implementation returns a straightforward implementation of the
275       * iterator interface, relying on the backing list's {@code size()},
276 <     * {@code get(int)}, and {@code remove(int)} methods.<p>
276 >     * {@code get(int)}, and {@code remove(int)} methods.
277       *
278 <     * Note that the iterator returned by this method will throw an
279 <     * {@code UnsupportedOperationException} in response to its
278 >     * <p>Note that the iterator returned by this method will throw an
279 >     * {@link UnsupportedOperationException} in response to its
280       * {@code remove} method unless the list's {@code remove(int)} method is
281 <     * overridden.<p>
281 >     * overridden.
282       *
283 <     * This implementation can be made to throw runtime exceptions in the face
284 <     * of concurrent modification, as described in the specification for the
285 <     * (protected) {@code modCount} field.
283 >     * <p>This implementation can be made to throw runtime exceptions in the
284 >     * face of concurrent modification, as described in the specification
285 >     * for the (protected) {@link #modCount} field.
286       *
287       * @return an iterator over the elements in this list in proper sequence
271     *
272     * @see #modCount
288       */
289      public Iterator<E> iterator() {
290 <        return new Itr();
290 >        return new Itr();
291      }
292  
293      /**
# Line 283 | Line 298 | public abstract class AbstractList<E> ex
298       * @see #listIterator(int)
299       */
300      public ListIterator<E> listIterator() {
301 <        return listIterator(0);
301 >        return listIterator(0);
302      }
303  
304      /**
# Line 293 | Line 308 | public abstract class AbstractList<E> ex
308       * {@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 <     * {@code get(int)}, {@code set(int, Object)}, {@code add(int, Object)}
311 >     * {@code get(int)}, {@code set(int, E)}, {@code add(int, E)}
312       * and {@code remove(int)} methods.
313       *
314       * <p>Note that the list iterator returned by this implementation will
315 <     * throw an {@code UnsupportedOperationException} in response to its
315 >     * throw an {@link UnsupportedOperationException} in response to its
316       * {@code remove}, {@code set} and {@code add} methods unless the
317 <     * list's {@code remove(int)}, {@code set(int, Object)}, and
318 <     * {@code add(int, Object)} methods are overridden.
317 >     * list's {@code remove(int)}, {@code set(int, E)}, and
318 >     * {@code add(int, E)} methods are overridden.
319       *
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 <     * the (protected) {@code modCount} field.
322 >     * the (protected) {@link #modCount} field.
323       *
324       * @throws IndexOutOfBoundsException {@inheritDoc}
310     *
311     * @see #modCount
325       */
326      public ListIterator<E> listIterator(final int index) {
327 <        if (index<0 || index>size())
315 <          throw new IndexOutOfBoundsException("Index: "+index);
327 >        rangeCheckForAdd(index);
328  
329 <        return new ListItr(index);
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;
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 <        public boolean hasNext() {
352 >        public boolean hasNext() {
353              return cursor != size();
354 <        }
354 >        }
355  
356 <        public E next() {
356 >        public E next() {
357              checkForComodification();
358 <            try {
359 <                E next = get(cursor);
360 <                lastRet = cursor++;
361 <                return next;
362 <            } catch (IndexOutOfBoundsException e) {
363 <                checkForComodification();
364 <                throw new NoSuchElementException();
365 <            }
366 <        }
367 <
368 <        public void remove() {
369 <            if (lastRet == -1)
370 <                throw new IllegalStateException();
358 >            try {
359 >                int i = cursor;
360 >                E next = get(i);
361 >                lastRet = i;
362 >                cursor = i + 1;
363 >                return next;
364 >            } catch (IndexOutOfBoundsException e) {
365 >                checkForComodification();
366 >                throw new NoSuchElementException();
367 >            }
368 >        }
369 >
370 >        public void remove() {
371 >            if (lastRet < 0)
372 >                throw new IllegalStateException();
373              checkForComodification();
374  
375 <            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 <
386 <        final void checkForComodification() {
387 <            if (modCount != expectedModCount)
388 <                throw new ConcurrentModificationException();
389 <        }
375 >            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 >
386 >        final void checkForComodification() {
387 >            if (modCount != expectedModCount)
388 >                throw new ConcurrentModificationException();
389 >        }
390      }
391  
392      private class ListItr extends Itr implements ListIterator<E> {
393 <        ListItr(int index) {
394 <            cursor = index;
395 <        }
396 <
397 <        public boolean hasPrevious() {
398 <            return cursor != 0;
399 <        }
393 >        ListItr(int index) {
394 >            cursor = index;
395 >        }
396 >
397 >        public boolean hasPrevious() {
398 >            return cursor != 0;
399 >        }
400  
401          public E previous() {
402              checkForComodification();
# Line 397 | Line 411 | public abstract class AbstractList<E> ex
411              }
412          }
413  
414 <        public int nextIndex() {
415 <            return cursor;
416 <        }
417 <
418 <        public int previousIndex() {
419 <            return cursor-1;
420 <        }
421 <
422 <        public void set(E e) {
423 <            if (lastRet == -1)
424 <                throw new IllegalStateException();
414 >        public int nextIndex() {
415 >            return cursor;
416 >        }
417 >
418 >        public int previousIndex() {
419 >            return cursor-1;
420 >        }
421 >
422 >        public void set(E e) {
423 >            if (lastRet < 0)
424 >                throw new IllegalStateException();
425              checkForComodification();
426  
427 <            try {
428 <                AbstractList.this.set(lastRet, e);
429 <                expectedModCount = modCount;
430 <            } catch (IndexOutOfBoundsException ex) {
431 <                throw new ConcurrentModificationException();
432 <            }
433 <        }
427 >            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) {
435 >        public void add(E e) {
436              checkForComodification();
437  
438 <            try {
438 >            try {
439                  int i = cursor;
440 <                AbstractList.this.add(i, e);
440 >                AbstractList.this.add(i, e);
441 >                lastRet = -1;
442                  cursor = i + 1;
443 <                lastRet = -1;
444 <                expectedModCount = modCount;
445 <            } catch (IndexOutOfBoundsException ex) {
446 <                throw new ConcurrentModificationException();
447 <            }
433 <        }
443 >                expectedModCount = modCount;
444 >            } catch (IndexOutOfBoundsException ex) {
445 >                throw new ConcurrentModificationException();
446 >            }
447 >        }
448      }
449  
450      /**
# Line 445 | Line 459 | public abstract class AbstractList<E> ex
459       * If this list implements {@code RandomAccess} the returned list will
460       * be an instance of the subclass that implements {@code RandomAccess}.
461       *
462 <     * <p>The subclass's {@code set(int, Object)}, {@code get(int)},
463 <     * {@code add(int, Object)}, {@code remove(int)}, {@code addAll(int,
462 >     * <p>The subclass's {@code set(int, E)}, {@code get(int)},
463 >     * {@code add(int, E)}, {@code remove(int)}, {@code addAll(int,
464       * Collection)} and {@code removeRange(int, int)} methods all
465       * delegate to the corresponding methods on the backing abstract list,
466       * after bounds-checking the index and adjusting for the offset.  The
# Line 463 | Line 477 | public abstract class AbstractList<E> ex
477       * the backing list is equal to its expected value, and throw a
478       * {@code ConcurrentModificationException} if it is not.
479       *
480 <     * @throws IndexOutOfBoundsException endpoint index value out of range
481 <     *         {@code (fromIndex &lt; 0 || toIndex &gt; size)}
480 >     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
481 >     *         {@code (fromIndex < 0 || toIndex > size)}
482       * @throws IllegalArgumentException if the endpoint indices are out of order
483 <     *         {@code (fromIndex &gt; toIndex)}
483 >     *         {@code (fromIndex > toIndex)}
484       */
485      public List<E> subList(int fromIndex, int toIndex) {
486          return (this instanceof RandomAccess ?
487 <                new RandomAccessSubList(this, this, fromIndex, fromIndex, toIndex) :
488 <                new SubList(this, this, fromIndex, fromIndex, toIndex));
487 >                new RandomAccessSubList<E>(this, fromIndex, toIndex) :
488 >                new SubList<E>(this, fromIndex, toIndex));
489      }
490  
491      // Comparison and hashing
# Line 498 | Line 512 | public abstract class AbstractList<E> ex
512       * @return {@code true} if the specified object is equal to this list
513       */
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());
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 <     * Returns the hash code value for this list. <p>
532 >     * Returns the hash code value for this list.
533       *
534 <     * This implementation uses exactly the code that is used to define the
534 >     * <p>This implementation uses exactly the code that is used to define the
535       * 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 <        Iterator<E> i = iterator();
543 <        while (i.hasNext()) {
544 <            E obj = i.next();
531 <            hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
532 <        }
533 <        return hashCode;
541 >        int hashCode = 1;
542 >        for (E e : this)
543 >            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
544 >        return hashCode;
545      }
546  
547      /**
548       * Removes from this list all of the elements whose index is between
549       * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
550       * Shifts any succeeding elements to the left (reduces their index).
551 <     * This call shortens the ArrayList by {@code (toIndex - fromIndex)}
552 <     * elements.  (If {@code toIndex==fromIndex}, this operation has no
542 <     * effect.)<p>
551 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
552 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
553       *
554 <     * This method is called by the {@code clear} operation on this list
554 >     * <p>This method is called by the {@code clear} operation on this list
555       * and its subLists.  Overriding this method to take advantage of
556       * the internals of the list implementation can <i>substantially</i>
557       * improve the performance of the {@code clear} operation on this list
558 <     * and its subLists.<p>
558 >     * and its subLists.
559       *
560 <     * This implementation gets a list iterator positioned before
560 >     * <p>This implementation gets a list iterator positioned before
561       * {@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
# Line 568 | Line 578 | public abstract class AbstractList<E> ex
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 <     * progress may yield incorrect results.<p>
581 >     * progress may yield incorrect results.
582       *
583 <     * This field is used by the iterator and list iterator implementation
583 >     * <p>This field is used by the iterator and list iterator implementation
584       * returned by the {@code iterator} and {@code listIterator} methods.
585       * If the value of this field changes unexpectedly, the iterator (or list
586       * 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       * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
590 <     * the face of concurrent modification during iteration.<p>
590 >     * the face of concurrent modification during iteration.
591       *
592 <     * <b>Use of this field by subclasses is optional.</b> If a subclass
592 >     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
593       * wishes to provide fail-fast iterators (and list iterators), then it
594 <     * merely has to increment this field in its {@code add(int, Object)} and
594 >     * merely has to increment this field in its {@code add(int, E)} and
595       * {@code remove(int)} methods (and any other methods that it overrides
596       * that result in structural modifications to the list).  A single call to
597 <     * {@code add(int, Object)} or {@code remove(int)} must add no more than
597 >     * {@code add(int, E)} or {@code remove(int)} must add no more than
598       * one to this field, or the iterators (and list iterators) will throw
599       * bogus {@code ConcurrentModificationExceptions}.  If an implementation
600       * does not wish to provide fail-fast iterators, this field may be
601       * ignored.
602       */
603      protected transient int modCount = 0;
604 +
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   }
614  
596 /**
597 * Generic sublists. Non-nested to enable construction by other
598 * classes in this package.
599 */
615   class SubList<E> extends AbstractList<E> {
616 <    /*
617 <     * A SubList has both a "base", the ultimate backing list, as well
618 <     * as a "parent", which is the list or sublist creating this
619 <     * sublist. All methods that may cause structural modifications
620 <     * 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 <            AbstractList<E> parent,
621 <            int baseIndex,
622 <            int fromIndex,
623 <            int toIndex) {
616 >    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          if (fromIndex < 0)
622              throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
623 <        if (toIndex > parent.size())
623 >        if (toIndex > list.size())
624              throw new IndexOutOfBoundsException("toIndex = " + toIndex);
625          if (fromIndex > toIndex)
626              throw new IllegalArgumentException("fromIndex(" + fromIndex +
627                                                 ") > toIndex(" + toIndex + ")");
628 <        this.base = base;
629 <        this.parent = parent;
630 <        this.baseOffset = baseIndex;
631 <        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 <        return new IndexOutOfBoundsException("Index: " + index +
644 <                                             ", Size: " + length);
628 >        l = list;
629 >        offset = fromIndex;
630 >        size = toIndex - fromIndex;
631 >        this.modCount = l.modCount;
632      }
633  
634      public E set(int index, E element) {
635 <        if (index < 0 || index >= length)
636 <            throw indexError(index);
637 <        if (base.modCount != modCount)
651 <            throw new ConcurrentModificationException();
652 <        return base.set(index + baseOffset, element);
635 >        rangeCheck(index);
636 >        checkForComodification();
637 >        return l.set(index+offset, element);
638      }
639  
640      public E get(int index) {
641 <        if (index < 0 || index >= length)
642 <            throw indexError(index);
643 <        if (base.modCount != modCount)
659 <            throw new ConcurrentModificationException();
660 <        return base.get(index + baseOffset);
641 >        rangeCheck(index);
642 >        checkForComodification();
643 >        return l.get(index+offset);
644      }
645  
646      public int size() {
647 <        if (base.modCount != modCount)
648 <            throw new ConcurrentModificationException();
666 <        return length;
647 >        checkForComodification();
648 >        return size;
649      }
650  
651      public void add(int index, E element) {
652 <        if (index < 0 || index>length)
653 <            throw indexError(index);
654 <        if (base.modCount != modCount)
655 <            throw new ConcurrentModificationException();
656 <        parent.add(index + parentOffset, element);
675 <        length++;
676 <        modCount = base.modCount;
652 >        rangeCheckForAdd(index);
653 >        checkForComodification();
654 >        l.add(index+offset, element);
655 >        this.modCount = l.modCount;
656 >        size++;
657      }
658  
659      public E remove(int index) {
660 <        if (index < 0 || index >= length)
661 <            throw indexError(index);
662 <        if (base.modCount != modCount)
663 <            throw new ConcurrentModificationException();
664 <        E result = parent.remove(index + parentOffset);
685 <        length--;
686 <        modCount = base.modCount;
660 >        rangeCheck(index);
661 >        checkForComodification();
662 >        E result = l.remove(index+offset);
663 >        this.modCount = l.modCount;
664 >        size--;
665          return result;
666      }
667  
668      protected void removeRange(int fromIndex, int toIndex) {
669 <        if (base.modCount != modCount)
670 <            throw new ConcurrentModificationException();
671 <        parent.removeRange(fromIndex + parentOffset, toIndex + parentOffset);
672 <        length -= (toIndex-fromIndex);
695 <        modCount = base.modCount;
669 >        checkForComodification();
670 >        l.removeRange(fromIndex+offset, toIndex+offset);
671 >        this.modCount = l.modCount;
672 >        size -= (toIndex-fromIndex);
673      }
674  
675      public boolean addAll(Collection<? extends E> c) {
676 <        return addAll(length, c);
676 >        return addAll(size, c);
677      }
678  
679      public boolean addAll(int index, Collection<? extends E> c) {
680 <        if (index < 0 || index > length)
704 <            throw indexError(index);
680 >        rangeCheckForAdd(index);
681          int cSize = c.size();
682          if (cSize==0)
683              return false;
684  
685 <        if (base.modCount != modCount)
686 <            throw new ConcurrentModificationException();
687 <        parent.addAll(parentOffset + index, c);
688 <        length += cSize;
713 <        modCount = base.modCount;
685 >        checkForComodification();
686 >        l.addAll(offset+index, c);
687 >        this.modCount = l.modCount;
688 >        size += cSize;
689          return true;
690      }
691  
717    public List<E> subList(int fromIndex, int toIndex) {
718        return new SubList(base, this, fromIndex + baseOffset,
719                           fromIndex, toIndex);
720    }
721
692      public Iterator<E> iterator() {
693 <        return new SubListIterator(this, 0);
693 >        return listIterator();
694      }
695  
696 <    public ListIterator<E> listIterator() {
697 <        return new SubListIterator(this, 0);
698 <    }
729 <
730 <    public ListIterator<E> listIterator(int index) {
731 <        if (index < 0 || index>length)
732 <            throw indexError(index);
733 <        return new SubListIterator(this, index);
734 <    }
696 >    public ListIterator<E> listIterator(final int index) {
697 >        checkForComodification();
698 >        rangeCheckForAdd(index);
699  
700 <    /**
701 <     * 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 <        int expectedModCount;         // Expected modCount of base
754 <
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 <        }
700 >        return new ListIterator<E>() {
701 >            private final ListIterator<E> i = l.listIterator(index+offset);
702  
703 <        public boolean hasNext() {
704 <            return cursor < fence;
705 <        }
703 >            public boolean hasNext() {
704 >                return nextIndex() < size;
705 >            }
706  
707 <        public boolean hasPrevious() {
708 <            return cursor > 0;
709 <        }
707 >            public E next() {
708 >                if (hasNext())
709 >                    return i.next();
710 >                else
711 >                    throw new NoSuchElementException();
712 >            }
713  
714 <        public int nextIndex() {
715 <            return cursor;
716 <        }
714 >            public boolean hasPrevious() {
715 >                return previousIndex() >= 0;
716 >            }
717  
718 <        public int previousIndex() {
719 <            return cursor - 1;
720 <        }
718 >            public E previous() {
719 >                if (hasPrevious())
720 >                    return i.previous();
721 >                else
722 >                    throw new NoSuchElementException();
723 >            }
724  
725 <        public E next() {
726 <            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 <                }
725 >            public int nextIndex() {
726 >                return i.nextIndex() - offset;
727              }
794            throw new ConcurrentModificationException();
795        }
728  
729 <        public E previous() {
730 <            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 <                }
729 >            public int previousIndex() {
730 >                return i.previousIndex() - offset;
731              }
810            throw new ConcurrentModificationException();
811        }
732  
733 <        public void set(E e) {
734 <            if (lastRet < 0)
735 <                throw new IllegalStateException();
736 <            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();
733 >            public void remove() {
734 >                i.remove();
735 >                SubList.this.modCount = l.modCount;
736 >                size--;
737              }
824        }
738  
739 <        public void remove() {
740 <            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();
739 >            public void set(E e) {
740 >                i.set(e);
741              }
842        }
742  
743 <        public void add(E e) {
744 <            if (expectedModCount != base.modCount)
745 <                throw new ConcurrentModificationException();
746 <            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();
743 >            public void add(E e) {
744 >                i.add(e);
745 >                SubList.this.modCount = l.modCount;
746 >                size++;
747              }
748 <        }
748 >        };
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 +
765 +    private String outOfBoundsMsg(int index) {
766 +        return "Index: "+index+", Size: "+size;
767 +    }
768 +
769 +    private void checkForComodification() {
770 +        if (this.modCount != l.modCount)
771 +            throw new ConcurrentModificationException();
772 +    }
773   }
774  
775   class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
776 <    RandomAccessSubList(AbstractList<E> base,
777 <                        AbstractList<E> parent, int baseIndex,
865 <                        int fromIndex, int toIndex) {
866 <        super(base, parent, baseIndex, fromIndex, toIndex);
776 >    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
777 >        super(list, fromIndex, toIndex);
778      }
779  
780      public List<E> subList(int fromIndex, int toIndex) {
781 <        return new RandomAccessSubList(base, this, fromIndex + baseOffset,
871 <                                       fromIndex, toIndex);
781 >        return new RandomAccessSubList<E>(this, fromIndex, toIndex);
782      }
783   }
874

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines