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.15 by jsr166, Mon Jun 26 01:27:51 2006 UTC vs.
Revision 1.20 by jsr166, Sun May 18 23:59:57 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;
# Line 47 | Line 65 | package java.util;
65   *
66   * @author  Josh Bloch
67   * @author  Neal Gafter
50 * @version %I%, %G%
68   * @since 1.2
69   */
70  
# Line 88 | Line 105 | public abstract class AbstractList<E> ex
105       *         prevents it from being added to this list
106       */
107      public boolean add(E e) {
108 <        add(size(), e);
109 <        return true;
108 >        add(size(), e);
109 >        return true;
110      }
111  
112      /**
# Line 112 | Line 129 | public abstract class AbstractList<E> ex
129       * @throws IndexOutOfBoundsException     {@inheritDoc}
130       */
131      public E set(int index, E element) {
132 <        throw new UnsupportedOperationException();
132 >        throw new UnsupportedOperationException();
133      }
134  
135      /**
# Line 128 | Line 145 | public abstract class AbstractList<E> ex
145       * @throws IndexOutOfBoundsException     {@inheritDoc}
146       */
147      public void add(int index, E element) {
148 <        throw new UnsupportedOperationException();
148 >        throw new UnsupportedOperationException();
149      }
150  
151      /**
# Line 141 | Line 158 | public abstract class AbstractList<E> ex
158       * @throws IndexOutOfBoundsException     {@inheritDoc}
159       */
160      public E remove(int index) {
161 <        throw new UnsupportedOperationException();
161 >        throw new UnsupportedOperationException();
162      }
163  
164  
# Line 158 | Line 175 | public abstract class AbstractList<E> ex
175       * @throws NullPointerException {@inheritDoc}
176       */
177      public int indexOf(Object o) {
178 <        ListIterator<E> e = listIterator();
179 <        if (o==null) {
180 <            while (e.hasNext())
181 <                if (e.next()==null)
182 <                    return e.previousIndex();
183 <        } else {
184 <            while (e.hasNext())
185 <                if (o.equals(e.next()))
186 <                    return e.previousIndex();
187 <        }
188 <        return -1;
178 >        ListIterator<E> e = listIterator();
179 >        if (o==null) {
180 >            while (e.hasNext())
181 >                if (e.next()==null)
182 >                    return e.previousIndex();
183 >        } else {
184 >            while (e.hasNext())
185 >                if (o.equals(e.next()))
186 >                    return e.previousIndex();
187 >        }
188 >        return -1;
189      }
190  
191      /**
# Line 183 | Line 200 | public abstract class AbstractList<E> ex
200       * @throws NullPointerException {@inheritDoc}
201       */
202      public int lastIndexOf(Object o) {
203 <        ListIterator<E> e = listIterator(size());
204 <        if (o==null) {
205 <            while (e.hasPrevious())
206 <                if (e.previous()==null)
207 <                    return e.nextIndex();
208 <        } else {
209 <            while (e.hasPrevious())
210 <                if (o.equals(e.previous()))
211 <                    return e.nextIndex();
212 <        }
213 <        return -1;
203 >        ListIterator<E> e = listIterator(size());
204 >        if (o==null) {
205 >            while (e.hasPrevious())
206 >                if (e.previous()==null)
207 >                    return e.nextIndex();
208 >        } else {
209 >            while (e.hasPrevious())
210 >                if (o.equals(e.previous()))
211 >                    return e.nextIndex();
212 >        }
213 >        return -1;
214      }
215  
216  
# Line 237 | Line 254 | public abstract class AbstractList<E> ex
254       * @throws IndexOutOfBoundsException     {@inheritDoc}
255       */
256      public boolean addAll(int index, Collection<? extends E> c) {
257 <        boolean modified = false;
258 <        Iterator<? extends E> e = c.iterator();
259 <        while (e.hasNext()) {
260 <            add(index++, e.next());
261 <            modified = true;
262 <        }
263 <        return modified;
257 >        rangeCheckForAdd(index);
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;
265      }
266  
267  
# Line 257 | Line 275 | public abstract class AbstractList<E> ex
275       * {@code get(int)}, and {@code remove(int)} methods.
276       *
277       * <p>Note that the iterator returned by this method will throw an
278 <     * {@code UnsupportedOperationException} in response to its
278 >     * {@link UnsupportedOperationException} in response to its
279       * {@code remove} method unless the list's {@code remove(int)} method is
280       * overridden.
281       *
282       * <p>This implementation can be made to throw runtime exceptions in the
283       * face of concurrent modification, as described in the specification
284 <     * for the (protected) {@code modCount} field.
284 >     * for the (protected) {@link #modCount} field.
285       *
286       * @return an iterator over the elements in this list in proper sequence
269     *
270     * @see #modCount
287       */
288      public Iterator<E> iterator() {
289 <        return new Itr();
289 >        return new Itr();
290      }
291  
292      /**
# Line 281 | Line 297 | public abstract class AbstractList<E> ex
297       * @see #listIterator(int)
298       */
299      public ListIterator<E> listIterator() {
300 <        return listIterator(0);
300 >        return listIterator(0);
301      }
302  
303      /**
# Line 295 | Line 311 | public abstract class AbstractList<E> ex
311       * and {@code remove(int)} methods.
312       *
313       * <p>Note that the list iterator returned by this implementation will
314 <     * throw an {@code UnsupportedOperationException} in response to its
314 >     * throw an {@link UnsupportedOperationException} in response to its
315       * {@code remove}, {@code set} and {@code add} methods unless the
316       * list's {@code remove(int)}, {@code set(int, E)}, and
317       * {@code add(int, E)} methods are overridden.
318       *
319       * <p>This implementation can be made to throw runtime exceptions in the
320       * face of concurrent modification, as described in the specification for
321 <     * the (protected) {@code modCount} field.
321 >     * the (protected) {@link #modCount} field.
322       *
323       * @throws IndexOutOfBoundsException {@inheritDoc}
308     *
309     * @see #modCount
324       */
325      public ListIterator<E> listIterator(final int index) {
326 <        if (index<0 || index>size())
313 <          throw new IndexOutOfBoundsException("Index: "+index);
326 >        rangeCheckForAdd(index);
327  
328 <        return new ListItr(index);
328 >        return new ListItr(index);
329      }
330  
331      private class Itr implements Iterator<E> {
332 <        /**
333 <         * Index of element to be returned by subsequent call to next.
334 <         */
335 <        int cursor = 0;
336 <
337 <        /**
338 <         * Index of element returned by most recent call to next or
339 <         * previous.  Reset to -1 if this element is deleted by a call
340 <         * to remove.
341 <         */
342 <        int lastRet = -1;
343 <
344 <        /**
345 <         * The modCount value that the iterator believes that the backing
346 <         * List should have.  If this expectation is violated, the iterator
347 <         * has detected concurrent modification.
348 <         */
349 <        int expectedModCount = modCount;
332 >        /**
333 >         * Index of element to be returned by subsequent call to next.
334 >         */
335 >        int cursor = 0;
336 >
337 >        /**
338 >         * Index of element returned by most recent call to next or
339 >         * previous.  Reset to -1 if this element is deleted by a call
340 >         * to remove.
341 >         */
342 >        int lastRet = -1;
343 >
344 >        /**
345 >         * The modCount value that the iterator believes that the backing
346 >         * List should have.  If this expectation is violated, the iterator
347 >         * has detected concurrent modification.
348 >         */
349 >        int expectedModCount = modCount;
350  
351 <        public boolean hasNext() {
351 >        public boolean hasNext() {
352              return cursor != size();
353 <        }
353 >        }
354  
355 <        public E next() {
355 >        public E next() {
356              checkForComodification();
357 <            try {
358 <                E next = get(cursor);
359 <                lastRet = cursor++;
360 <                return next;
361 <            } catch (IndexOutOfBoundsException e) {
362 <                checkForComodification();
363 <                throw new NoSuchElementException();
364 <            }
365 <        }
366 <
367 <        public void remove() {
368 <            if (lastRet == -1)
369 <                throw new IllegalStateException();
357 >            try {
358 >                int i = cursor;
359 >                E next = get(i);
360 >                lastRet = i;
361 >                cursor = i + 1;
362 >                return next;
363 >            } catch (IndexOutOfBoundsException e) {
364 >                checkForComodification();
365 >                throw new NoSuchElementException();
366 >            }
367 >        }
368 >
369 >        public void remove() {
370 >            if (lastRet < 0)
371 >                throw new IllegalStateException();
372              checkForComodification();
373  
374 <            try {
375 <                AbstractList.this.remove(lastRet);
376 <                if (lastRet < cursor)
377 <                    cursor--;
378 <                lastRet = -1;
379 <                expectedModCount = modCount;
380 <            } catch (IndexOutOfBoundsException e) {
381 <                throw new ConcurrentModificationException();
382 <            }
383 <        }
384 <
385 <        final void checkForComodification() {
386 <            if (modCount != expectedModCount)
387 <                throw new ConcurrentModificationException();
388 <        }
374 >            try {
375 >                AbstractList.this.remove(lastRet);
376 >                if (lastRet < cursor)
377 >                    cursor--;
378 >                lastRet = -1;
379 >                expectedModCount = modCount;
380 >            } catch (IndexOutOfBoundsException e) {
381 >                throw new ConcurrentModificationException();
382 >            }
383 >        }
384 >
385 >        final void checkForComodification() {
386 >            if (modCount != expectedModCount)
387 >                throw new ConcurrentModificationException();
388 >        }
389      }
390  
391      private class ListItr extends Itr implements ListIterator<E> {
392 <        ListItr(int index) {
393 <            cursor = index;
394 <        }
395 <
396 <        public boolean hasPrevious() {
397 <            return cursor != 0;
398 <        }
392 >        ListItr(int index) {
393 >            cursor = index;
394 >        }
395 >
396 >        public boolean hasPrevious() {
397 >            return cursor != 0;
398 >        }
399  
400          public E previous() {
401              checkForComodification();
# Line 395 | Line 410 | public abstract class AbstractList<E> ex
410              }
411          }
412  
413 <        public int nextIndex() {
414 <            return cursor;
415 <        }
416 <
417 <        public int previousIndex() {
418 <            return cursor-1;
419 <        }
420 <
421 <        public void set(E e) {
422 <            if (lastRet == -1)
423 <                throw new IllegalStateException();
413 >        public int nextIndex() {
414 >            return cursor;
415 >        }
416 >
417 >        public int previousIndex() {
418 >            return cursor-1;
419 >        }
420 >
421 >        public void set(E e) {
422 >            if (lastRet < 0)
423 >                throw new IllegalStateException();
424              checkForComodification();
425  
426 <            try {
427 <                AbstractList.this.set(lastRet, e);
428 <                expectedModCount = modCount;
429 <            } catch (IndexOutOfBoundsException ex) {
430 <                throw new ConcurrentModificationException();
431 <            }
432 <        }
426 >            try {
427 >                AbstractList.this.set(lastRet, e);
428 >                expectedModCount = modCount;
429 >            } catch (IndexOutOfBoundsException ex) {
430 >                throw new ConcurrentModificationException();
431 >            }
432 >        }
433  
434 <        public void add(E e) {
434 >        public void add(E e) {
435              checkForComodification();
436  
437 <            try {
437 >            try {
438                  int i = cursor;
439 <                AbstractList.this.add(i, e);
439 >                AbstractList.this.add(i, e);
440 >                lastRet = -1;
441                  cursor = i + 1;
442 <                lastRet = -1;
443 <                expectedModCount = modCount;
444 <            } catch (IndexOutOfBoundsException ex) {
445 <                throw new ConcurrentModificationException();
446 <            }
431 <        }
442 >                expectedModCount = modCount;
443 >            } catch (IndexOutOfBoundsException ex) {
444 >                throw new ConcurrentModificationException();
445 >            }
446 >        }
447      }
448  
449      /**
# Line 461 | Line 476 | public abstract class AbstractList<E> ex
476       * the backing list is equal to its expected value, and throw a
477       * {@code ConcurrentModificationException} if it is not.
478       *
479 <     * @throws IndexOutOfBoundsException endpoint index value out of range
479 >     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
480       *         {@code (fromIndex < 0 || toIndex > size)}
481       * @throws IllegalArgumentException if the endpoint indices are out of order
482       *         {@code (fromIndex > toIndex)}
483       */
484      public List<E> subList(int fromIndex, int toIndex) {
485          return (this instanceof RandomAccess ?
486 <                new RandomAccessSubList(this, this, fromIndex, fromIndex, toIndex) :
487 <                new SubList(this, this, fromIndex, fromIndex, toIndex));
486 >                new RandomAccessSubList<E>(this, fromIndex, toIndex) :
487 >                new SubList<E>(this, fromIndex, toIndex));
488      }
489  
490      // Comparison and hashing
# Line 481 | Line 496 | public abstract class AbstractList<E> ex
496       * the two lists are <i>equal</i>.  (Two elements {@code e1} and
497       * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null :
498       * e1.equals(e2))}.)  In other words, two lists are defined to be
499 <     * equal if they contain the same elements in the same order.
499 >     * equal if they contain the same elements in the same order.<p>
500       *
501 <     * <p>This implementation first checks if the specified object is this
501 >     * This implementation first checks if the specified object is this
502       * list. If so, it returns {@code true}; if not, it checks if the
503       * specified object is a list. If not, it returns {@code false}; if so,
504       * it iterates over both lists, comparing corresponding pairs of elements.
# Line 496 | Line 511 | public abstract class AbstractList<E> ex
511       * @return {@code true} if the specified object is equal to this list
512       */
513      public boolean equals(Object o) {
514 <        if (o == this)
515 <            return true;
516 <        if (!(o instanceof List))
517 <            return false;
518 <
519 <        ListIterator<E> e1 = listIterator();
520 <        ListIterator e2 = ((List) o).listIterator();
521 <        while(e1.hasNext() && e2.hasNext()) {
522 <            E o1 = e1.next();
523 <            Object o2 = e2.next();
524 <            if (!(o1==null ? o2==null : o1.equals(o2)))
525 <                return false;
526 <        }
527 <        return !(e1.hasNext() || e2.hasNext());
514 >        if (o == this)
515 >            return true;
516 >        if (!(o instanceof List))
517 >            return false;
518 >
519 >        ListIterator<E> e1 = listIterator();
520 >        ListIterator e2 = ((List) o).listIterator();
521 >        while(e1.hasNext() && e2.hasNext()) {
522 >            E o1 = e1.next();
523 >            Object o2 = e2.next();
524 >            if (!(o1==null ? o2==null : o1.equals(o2)))
525 >                return false;
526 >        }
527 >        return !(e1.hasNext() || e2.hasNext());
528      }
529  
530      /**
# Line 522 | Line 537 | public abstract class AbstractList<E> ex
537       * @return the hash code value for this list
538       */
539      public int hashCode() {
540 <        int hashCode = 1;
541 <        Iterator<E> i = iterator();
542 <        while (i.hasNext()) {
543 <            E obj = i.next();
529 <            hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
530 <        }
531 <        return hashCode;
540 >        int hashCode = 1;
541 >        for (E e : this)
542 >            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
543 >        return hashCode;
544      }
545  
546      /**
547       * Removes from this list all of the elements whose index is between
548       * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
549       * Shifts any succeeding elements to the left (reduces their index).
550 <     * This call shortens the ArrayList by {@code (toIndex - fromIndex)}
551 <     * elements.  (If {@code toIndex==fromIndex}, this operation has no
540 <     * effect.)
550 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
551 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
552       *
553       * <p>This method is called by the {@code clear} operation on this list
554       * and its subLists.  Overriding this method to take advantage of
# Line 589 | Line 600 | public abstract class AbstractList<E> ex
600       * ignored.
601       */
602      protected transient int modCount = 0;
603 +
604 +    private void rangeCheckForAdd(int index) {
605 +        if (index < 0 || index > size())
606 +            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
607 +    }
608 +
609 +    private String outOfBoundsMsg(int index) {
610 +        return "Index: "+index+", Size: "+size();
611 +    }
612   }
613  
594 /**
595 * Generic sublists. Non-nested to enable construction by other
596 * classes in this package.
597 */
614   class SubList<E> extends AbstractList<E> {
615 <    /*
616 <     * A SubList has both a "base", the ultimate backing list, as well
617 <     * as a "parent", which is the list or sublist creating this
618 <     * sublist. All methods that may cause structural modifications
619 <     * must propagate through the parent link, with O(k) performance
604 <     * where k is sublist depth. For example in the case of a
605 <     * sub-sub-list, invoking remove(x) will result in a chain of
606 <     * three remove calls. However, all other non-structurally
607 <     * modifying methods can bypass this chain, and relay directly to
608 <     * the base list. In particular, doing so signficantly speeds up
609 <     * the performance of iterators for deeply-nested sublists.
610 <     */
611 <    final AbstractList<E> base;   // Backing list
612 <    final AbstractList<E> parent; // Parent list
613 <    final int baseOffset;         // index wrt base
614 <    final int parentOffset;       // index wrt parent
615 <    int length;                   // Number of elements in this sublist
616 <
617 <    SubList(AbstractList<E> base,
618 <            AbstractList<E> parent,
619 <            int baseIndex,
620 <            int fromIndex,
621 <            int toIndex) {
615 >    private final AbstractList<E> l;
616 >    private final int offset;
617 >    private int size;
618 >
619 >    SubList(AbstractList<E> list, int fromIndex, int toIndex) {
620          if (fromIndex < 0)
621              throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
622 <        if (toIndex > parent.size())
622 >        if (toIndex > list.size())
623              throw new IndexOutOfBoundsException("toIndex = " + toIndex);
624          if (fromIndex > toIndex)
625              throw new IllegalArgumentException("fromIndex(" + fromIndex +
626                                                 ") > toIndex(" + toIndex + ")");
627 <        this.base = base;
628 <        this.parent = parent;
629 <        this.baseOffset = baseIndex;
630 <        this.parentOffset = fromIndex;
633 <        this.length = toIndex - fromIndex;
634 <        this.modCount = base.modCount;
635 <    }
636 <
637 <    /**
638 <     * Returns an IndexOutOfBoundsException with nicer message
639 <     */
640 <    private IndexOutOfBoundsException indexError(int index) {
641 <        return new IndexOutOfBoundsException("Index: " + index +
642 <                                             ", Size: " + length);
627 >        l = list;
628 >        offset = fromIndex;
629 >        size = toIndex - fromIndex;
630 >        this.modCount = l.modCount;
631      }
632  
633      public E set(int index, E element) {
634 <        if (index < 0 || index >= length)
635 <            throw indexError(index);
636 <        if (base.modCount != modCount)
649 <            throw new ConcurrentModificationException();
650 <        return base.set(index + baseOffset, element);
634 >        rangeCheck(index);
635 >        checkForComodification();
636 >        return l.set(index+offset, element);
637      }
638  
639      public E get(int index) {
640 <        if (index < 0 || index >= length)
641 <            throw indexError(index);
642 <        if (base.modCount != modCount)
657 <            throw new ConcurrentModificationException();
658 <        return base.get(index + baseOffset);
640 >        rangeCheck(index);
641 >        checkForComodification();
642 >        return l.get(index+offset);
643      }
644  
645      public int size() {
646 <        if (base.modCount != modCount)
647 <            throw new ConcurrentModificationException();
664 <        return length;
646 >        checkForComodification();
647 >        return size;
648      }
649  
650      public void add(int index, E element) {
651 <        if (index < 0 || index>length)
652 <            throw indexError(index);
653 <        if (base.modCount != modCount)
654 <            throw new ConcurrentModificationException();
655 <        parent.add(index + parentOffset, element);
673 <        length++;
674 <        modCount = base.modCount;
651 >        rangeCheckForAdd(index);
652 >        checkForComodification();
653 >        l.add(index+offset, element);
654 >        this.modCount = l.modCount;
655 >        size++;
656      }
657  
658      public E remove(int index) {
659 <        if (index < 0 || index >= length)
660 <            throw indexError(index);
661 <        if (base.modCount != modCount)
662 <            throw new ConcurrentModificationException();
663 <        E result = parent.remove(index + parentOffset);
683 <        length--;
684 <        modCount = base.modCount;
659 >        rangeCheck(index);
660 >        checkForComodification();
661 >        E result = l.remove(index+offset);
662 >        this.modCount = l.modCount;
663 >        size--;
664          return result;
665      }
666  
667      protected void removeRange(int fromIndex, int toIndex) {
668 <        if (base.modCount != modCount)
669 <            throw new ConcurrentModificationException();
670 <        parent.removeRange(fromIndex + parentOffset, toIndex + parentOffset);
671 <        length -= (toIndex-fromIndex);
693 <        modCount = base.modCount;
668 >        checkForComodification();
669 >        l.removeRange(fromIndex+offset, toIndex+offset);
670 >        this.modCount = l.modCount;
671 >        size -= (toIndex-fromIndex);
672      }
673  
674      public boolean addAll(Collection<? extends E> c) {
675 <        return addAll(length, c);
675 >        return addAll(size, c);
676      }
677  
678      public boolean addAll(int index, Collection<? extends E> c) {
679 <        if (index < 0 || index > length)
702 <            throw indexError(index);
679 >        rangeCheckForAdd(index);
680          int cSize = c.size();
681          if (cSize==0)
682              return false;
683  
684 <        if (base.modCount != modCount)
685 <            throw new ConcurrentModificationException();
686 <        parent.addAll(parentOffset + index, c);
687 <        length += cSize;
711 <        modCount = base.modCount;
684 >        checkForComodification();
685 >        l.addAll(offset+index, c);
686 >        this.modCount = l.modCount;
687 >        size += cSize;
688          return true;
689      }
690  
715    public List<E> subList(int fromIndex, int toIndex) {
716        return new SubList(base, this, fromIndex + baseOffset,
717                           fromIndex, toIndex);
718    }
719
691      public Iterator<E> iterator() {
692 <        return new SubListIterator(this, 0);
692 >        return listIterator();
693      }
694  
695 <    public ListIterator<E> listIterator() {
696 <        return new SubListIterator(this, 0);
697 <    }
695 >    public ListIterator<E> listIterator(final int index) {
696 >        checkForComodification();
697 >        rangeCheckForAdd(index);
698  
699 <    public ListIterator<E> listIterator(int index) {
700 <        if (index < 0 || index>length)
730 <            throw indexError(index);
731 <        return new SubListIterator(this, index);
732 <    }
699 >        return new ListIterator<E>() {
700 >            private final ListIterator<E> i = l.listIterator(index+offset);
701  
702 <    /**
703 <     * Generic sublist iterator obeying fastfail semantics via
704 <     * modCount.  The hasNext and next methods locally check for
737 <     * in-range indices before relaying to backing list to get
738 <     * element. If this either encounters an unexpected modCount or
739 <     * fails, the backing list must have been concurrently modified,
740 <     * and is so reported.  The add and remove methods performing
741 <     * structural modifications instead relay them through the
742 <     * sublist.
743 <     */
744 <    private static final class SubListIterator<E> implements ListIterator<E> {
745 <        final SubList<E> outer;       // Sublist creating this iteraor
746 <        final AbstractList<E> base;   // base list
747 <        final int offset;             // Cursor offset wrt base
748 <        int cursor;                   // Current index
749 <        int fence;                    // Upper bound on cursor
750 <        int lastRet;                  // Index of returned element, or -1
751 <        int expectedModCount;         // Expected modCount of base
752 <
753 <        SubListIterator(SubList<E> list, int index) {
754 <            this.lastRet = -1;
755 <            this.cursor = index;
756 <            this.outer = list;
757 <            this.offset = list.baseOffset;
758 <            this.fence = list.length;
759 <            this.base = list.base;
760 <            this.expectedModCount = base.modCount;
761 <        }
762 <
763 <        public boolean hasNext() {
764 <            return cursor < fence;
765 <        }
702 >            public boolean hasNext() {
703 >                return nextIndex() < size;
704 >            }
705  
706 <        public boolean hasPrevious() {
707 <            return cursor > 0;
708 <        }
706 >            public E next() {
707 >                if (hasNext())
708 >                    return i.next();
709 >                else
710 >                    throw new NoSuchElementException();
711 >            }
712  
713 <        public int nextIndex() {
714 <            return cursor;
715 <        }
713 >            public boolean hasPrevious() {
714 >                return previousIndex() >= 0;
715 >            }
716  
717 <        public int previousIndex() {
718 <            return cursor - 1;
719 <        }
717 >            public E previous() {
718 >                if (hasPrevious())
719 >                    return i.previous();
720 >                else
721 >                    throw new NoSuchElementException();
722 >            }
723  
724 <        public E next() {
725 <            int i = cursor;
781 <            if (cursor >= fence)
782 <                throw new NoSuchElementException();
783 <            if (expectedModCount == base.modCount) {
784 <                try {
785 <                    Object next = base.get(i + offset);
786 <                    lastRet = i;
787 <                    cursor = i + 1;
788 <                    return (E)next;
789 <                } catch (IndexOutOfBoundsException fallThrough) {
790 <                }
724 >            public int nextIndex() {
725 >                return i.nextIndex() - offset;
726              }
792            throw new ConcurrentModificationException();
793        }
727  
728 <        public E previous() {
729 <            int i = cursor - 1;
797 <            if (i < 0)
798 <                throw new NoSuchElementException();
799 <            if (expectedModCount == base.modCount) {
800 <                try {
801 <                    Object prev = base.get(i + offset);
802 <                    lastRet = i;
803 <                    cursor = i;
804 <                    return (E)prev;
805 <                } catch (IndexOutOfBoundsException fallThrough) {
806 <                }
728 >            public int previousIndex() {
729 >                return i.previousIndex() - offset;
730              }
808            throw new ConcurrentModificationException();
809        }
731  
732 <        public void set(E e) {
733 <            if (lastRet < 0)
734 <                throw new IllegalStateException();
735 <            if (expectedModCount != base.modCount)
815 <                throw new ConcurrentModificationException();
816 <            try {
817 <                outer.set(lastRet, e);
818 <                expectedModCount = base.modCount;
819 <            } catch (IndexOutOfBoundsException ex) {
820 <                throw new ConcurrentModificationException();
732 >            public void remove() {
733 >                i.remove();
734 >                SubList.this.modCount = l.modCount;
735 >                size--;
736              }
822        }
737  
738 <        public void remove() {
739 <            int i = lastRet;
826 <            if (i < 0)
827 <                throw new IllegalStateException();
828 <            if (expectedModCount != base.modCount)
829 <                throw new ConcurrentModificationException();
830 <            try {
831 <                outer.remove(i);
832 <                if (i < cursor)
833 <                    cursor--;
834 <                lastRet = -1;
835 <                fence = outer.length;
836 <                expectedModCount = base.modCount;
837 <            } catch (IndexOutOfBoundsException ex) {
838 <                throw new ConcurrentModificationException();
738 >            public void set(E e) {
739 >                i.set(e);
740              }
840        }
741  
742 <        public void add(E e) {
743 <            if (expectedModCount != base.modCount)
744 <                throw new ConcurrentModificationException();
745 <            try {
846 <                int i = cursor;
847 <                outer.add(i, e);
848 <                cursor = i + 1;
849 <                lastRet = -1;
850 <                fence = outer.length;
851 <                expectedModCount = base.modCount;
852 <            } catch (IndexOutOfBoundsException ex) {
853 <                throw new ConcurrentModificationException();
742 >            public void add(E e) {
743 >                i.add(e);
744 >                SubList.this.modCount = l.modCount;
745 >                size++;
746              }
747 <        }
747 >        };
748 >    }
749 >
750 >    public List<E> subList(int fromIndex, int toIndex) {
751 >        return new SubList<E>(this, fromIndex, toIndex);
752 >    }
753 >
754 >    private void rangeCheck(int index) {
755 >        if (index < 0 || index >= size)
756 >            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
757 >    }
758 >
759 >    private void rangeCheckForAdd(int index) {
760 >        if (index < 0 || index > size)
761 >            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
762      }
763  
764 +    private String outOfBoundsMsg(int index) {
765 +        return "Index: "+index+", Size: "+size;
766 +    }
767 +
768 +    private void checkForComodification() {
769 +        if (this.modCount != l.modCount)
770 +            throw new ConcurrentModificationException();
771 +    }
772   }
773  
774   class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
775 <    RandomAccessSubList(AbstractList<E> base,
776 <                        AbstractList<E> parent, int baseIndex,
863 <                        int fromIndex, int toIndex) {
864 <        super(base, parent, baseIndex, fromIndex, toIndex);
775 >    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
776 >        super(list, fromIndex, toIndex);
777      }
778  
779      public List<E> subList(int fromIndex, int toIndex) {
780 <        return new RandomAccessSubList(base, this, fromIndex + baseOffset,
869 <                                       fromIndex, toIndex);
780 >        return new RandomAccessSubList<E>(this, fromIndex, toIndex);
781      }
782   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines