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.16 by jsr166, Sun Jan 7 07:38:27 2007 UTC vs.
Revision 1.18 by jsr166, Tue Sep 11 15:24:16 2007 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 2007 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 237 | Line 255 | public abstract class AbstractList<E> ex
255       * @throws IndexOutOfBoundsException     {@inheritDoc}
256       */
257      public boolean addAll(int index, Collection<? extends E> c) {
258 +        rangeCheckForAdd(index);
259          boolean modified = false;
260          Iterator<? extends E> e = c.iterator();
261          while (e.hasNext()) {
# Line 257 | Line 276 | public abstract class AbstractList<E> ex
276       * {@code get(int)}, and {@code remove(int)} methods.
277       *
278       * <p>Note that the iterator returned by this method will throw an
279 <     * {@code UnsupportedOperationException} in response to its
279 >     * {@link UnsupportedOperationException} in response to its
280       * {@code remove} method unless the list's {@code remove(int)} method is
281       * overridden.
282       *
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) {@code modCount} field.
285 >     * for the (protected) {@link #modCount} field.
286       *
287       * @return an iterator over the elements in this list in proper sequence
269     *
270     * @see #modCount
288       */
289      public Iterator<E> iterator() {
290          return new Itr();
# Line 295 | Line 312 | public abstract class AbstractList<E> ex
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, 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}
308     *
309     * @see #modCount
325       */
326      public ListIterator<E> listIterator(final int index) {
327 <        if (index<0 || index>size())
313 <          throw new IndexOutOfBoundsException("Index: "+index);
327 >        rangeCheckForAdd(index);
328  
329          return new ListItr(index);
330      }
# Line 342 | Line 356 | public abstract class AbstractList<E> ex
356          public E next() {
357              checkForComodification();
358              try {
359 <                E next = get(cursor);
360 <                lastRet = cursor++;
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();
# Line 352 | Line 368 | public abstract class AbstractList<E> ex
368          }
369  
370          public void remove() {
371 <            if (lastRet == -1)
371 >            if (lastRet < 0)
372                  throw new IllegalStateException();
373              checkForComodification();
374  
# Line 404 | Line 420 | public abstract class AbstractList<E> ex
420          }
421  
422          public void set(E e) {
423 <            if (lastRet == -1)
423 >            if (lastRet < 0)
424                  throw new IllegalStateException();
425              checkForComodification();
426  
# Line 420 | Line 436 | public abstract class AbstractList<E> ex
436              checkForComodification();
437  
438              try {
439 <                int i = cursor;
439 >                int i = cursor;
440                  AbstractList.this.add(i, e);
425                cursor = i + 1;
441                  lastRet = -1;
442 +                cursor = i + 1;
443                  expectedModCount = modCount;
444              } catch (IndexOutOfBoundsException ex) {
445                  throw new ConcurrentModificationException();
# Line 461 | 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
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 > 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 481 | Line 497 | public abstract class AbstractList<E> ex
497       * the two lists are <i>equal</i>.  (Two elements {@code e1} and
498       * {@code e2} are <i>equal</i> if {@code (e1==null ? e2==null :
499       * e1.equals(e2))}.)  In other words, two lists are defined to be
500 <     * equal if they contain the same elements in the same order.
500 >     * equal if they contain the same elements in the same order.<p>
501       *
502 <     * <p>This implementation first checks if the specified object is this
502 >     * This implementation first checks if the specified object is this
503       * list. If so, it returns {@code true}; if not, it checks if the
504       * specified object is a list. If not, it returns {@code false}; if so,
505       * it iterates over both lists, comparing corresponding pairs of elements.
# Line 523 | Line 539 | public abstract class AbstractList<E> ex
539       */
540      public int hashCode() {
541          int hashCode = 1;
542 <        Iterator<E> i = iterator();
543 <        while (i.hasNext()) {
528 <            E obj = i.next();
529 <            hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
530 <        }
542 >        for (E e : this)
543 >            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
544          return hashCode;
545      }
546  
# Line 535 | Line 548 | public abstract class AbstractList<E> ex
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
540 <     * effect.)
551 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
552 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
553       *
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
# Line 589 | Line 601 | public abstract class AbstractList<E> ex
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  
594 /**
595 * Generic sublists. Non-nested to enable construction by other
596 * classes in this package.
597 */
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
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) {
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;
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);
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)
649 <            throw new ConcurrentModificationException();
650 <        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)
657 <            throw new ConcurrentModificationException();
658 <        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();
664 <        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);
673 <        length++;
674 <        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);
683 <        length--;
684 <        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);
693 <        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)
702 <            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;
711 <        modCount = base.modCount;
685 >        checkForComodification();
686 >        l.addAll(offset+index, c);
687 >        this.modCount = l.modCount;
688 >        size += cSize;
689          return true;
690      }
691  
715    public List<E> subList(int fromIndex, int toIndex) {
716        return new SubList(base, this, fromIndex + baseOffset,
717                           fromIndex, toIndex);
718    }
719
692      public Iterator<E> iterator() {
693 <        return new SubListIterator(this, 0);
722 <    }
723 <
724 <    public ListIterator<E> listIterator() {
725 <        return new SubListIterator(this, 0);
693 >        return listIterator();
694      }
695  
696 <    public ListIterator<E> listIterator(int index) {
697 <        if (index < 0 || index>length)
698 <            throw indexError(index);
731 <        return new SubListIterator(this, index);
732 <    }
696 >    public ListIterator<E> listIterator(final int index) {
697 >        checkForComodification();
698 >        rangeCheckForAdd(index);
699  
700 <    /**
701 <     * Generic sublist iterator obeying fastfail semantics via
736 <     * 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 <        }
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;
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 <                }
725 >            public int nextIndex() {
726 >                return i.nextIndex() - offset;
727              }
792            throw new ConcurrentModificationException();
793        }
728  
729 <        public E previous() {
730 <            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 <                }
729 >            public int previousIndex() {
730 >                return i.previousIndex() - offset;
731              }
808            throw new ConcurrentModificationException();
809        }
732  
733 <        public void set(E e) {
734 <            if (lastRet < 0)
735 <                throw new IllegalStateException();
736 <            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();
733 >            public void remove() {
734 >                i.remove();
735 >                SubList.this.modCount = l.modCount;
736 >                size--;
737              }
822        }
738  
739 <        public void remove() {
740 <            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();
739 >            public void set(E e) {
740 >                i.set(e);
741              }
840        }
742  
743 <        public void add(E e) {
744 <            if (expectedModCount != base.modCount)
745 <                throw new ConcurrentModificationException();
746 <            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();
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,
863 <                        int fromIndex, int toIndex) {
864 <        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,
869 <                                       fromIndex, toIndex);
781 >        return new RandomAccessSubList<E>(this, fromIndex, toIndex);
782      }
783   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines