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

Comparing jsr166/src/main/java/util/ArrayList.java (file contents):
Revision 1.34 by jsr166, Tue Oct 18 17:31:18 2016 UTC vs.
Revision 1.68 by jsr166, Sat Aug 10 16:48:05 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
2 > * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5   * This code is free software; you can redistribute it and/or modify it
# Line 28 | Line 28 | package java.util;
28   import java.util.function.Consumer;
29   import java.util.function.Predicate;
30   import java.util.function.UnaryOperator;
31 + // OPENJDK import jdk.internal.access.SharedSecrets;
32 + import jdk.internal.util.ArraysSupport;
33  
34   /**
35   * Resizable-array implementation of the {@code List} interface.  Implements
# Line 91 | Line 93 | import java.util.function.UnaryOperator;
93   * should be used only to detect bugs.</i>
94   *
95   * <p>This class is a member of the
96 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
96 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
97   * Java Collections Framework</a>.
98   *
99   * @param <E> the type of elements in this list
# Line 104 | Line 106 | import java.util.function.UnaryOperator;
106   * @see     Vector
107   * @since   1.2
108   */
107
109   public class ArrayList<E> extends AbstractList<E>
110          implements List<E>, RandomAccess, Cloneable, java.io.Serializable
111   {
# Line 219 | Line 220 | public class ArrayList<E> extends Abstra
220      }
221  
222      /**
222     * The maximum size of array to allocate (unless necessary).
223     * Some VMs reserve some header words in an array.
224     * Attempts to allocate larger arrays may result in
225     * OutOfMemoryError: Requested array size exceeds VM limit
226     */
227    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
228
229    /**
223       * Increases the capacity to ensure that it can hold at least the
224       * number of elements specified by the minimum capacity argument.
225       *
# Line 234 | Line 227 | public class ArrayList<E> extends Abstra
227       * @throws OutOfMemoryError if minCapacity is less than zero
228       */
229      private Object[] grow(int minCapacity) {
230 <        return elementData = Arrays.copyOf(elementData,
231 <                                           newCapacity(minCapacity));
230 >        int oldCapacity = elementData.length;
231 >        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
232 >            int newCapacity = ArraysSupport.newLength(oldCapacity,
233 >                    minCapacity - oldCapacity, /* minimum growth */
234 >                    oldCapacity >> 1           /* preferred growth */);
235 >            return elementData = Arrays.copyOf(elementData, newCapacity);
236 >        } else {
237 >            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
238 >        }
239      }
240  
241      private Object[] grow() {
# Line 243 | Line 243 | public class ArrayList<E> extends Abstra
243      }
244  
245      /**
246     * Returns a capacity at least as large as the given minimum capacity.
247     * Returns the current capacity increased by 50% if that suffices.
248     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
249     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
250     *
251     * @param minCapacity the desired minimum capacity
252     * @throws OutOfMemoryError if minCapacity is less than zero
253     */
254    private int newCapacity(int minCapacity) {
255        // overflow-conscious code
256        int oldCapacity = elementData.length;
257        int newCapacity = oldCapacity + (oldCapacity >> 1);
258        if (newCapacity - minCapacity <= 0) {
259            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
260                return Math.max(DEFAULT_CAPACITY, minCapacity);
261            if (minCapacity < 0) // overflow
262                throw new OutOfMemoryError();
263            return minCapacity;
264        }
265        return (newCapacity - MAX_ARRAY_SIZE <= 0)
266            ? newCapacity
267            : hugeCapacity(minCapacity);
268    }
269
270    private static int hugeCapacity(int minCapacity) {
271        if (minCapacity < 0) // overflow
272            throw new OutOfMemoryError();
273        return (minCapacity > MAX_ARRAY_SIZE)
274            ? Integer.MAX_VALUE
275            : MAX_ARRAY_SIZE;
276    }
277
278    /**
246       * Returns the number of elements in this list.
247       *
248       * @return the number of elements in this list
# Line 314 | Line 281 | public class ArrayList<E> extends Abstra
281       * or -1 if there is no such index.
282       */
283      public int indexOf(Object o) {
284 +        return indexOfRange(o, 0, size);
285 +    }
286 +
287 +    int indexOfRange(Object o, int start, int end) {
288 +        Object[] es = elementData;
289          if (o == null) {
290 <            for (int i = 0; i < size; i++)
291 <                if (elementData[i]==null)
290 >            for (int i = start; i < end; i++) {
291 >                if (es[i] == null) {
292                      return i;
293 +                }
294 +            }
295          } else {
296 <            for (int i = 0; i < size; i++)
297 <                if (o.equals(elementData[i]))
296 >            for (int i = start; i < end; i++) {
297 >                if (o.equals(es[i])) {
298                      return i;
299 +                }
300 +            }
301          }
302          return -1;
303      }
# Line 334 | Line 310 | public class ArrayList<E> extends Abstra
310       * or -1 if there is no such index.
311       */
312      public int lastIndexOf(Object o) {
313 +        return lastIndexOfRange(o, 0, size);
314 +    }
315 +
316 +    int lastIndexOfRange(Object o, int start, int end) {
317 +        Object[] es = elementData;
318          if (o == null) {
319 <            for (int i = size-1; i >= 0; i--)
320 <                if (elementData[i]==null)
319 >            for (int i = end - 1; i >= start; i--) {
320 >                if (es[i] == null) {
321                      return i;
322 +                }
323 +            }
324          } else {
325 <            for (int i = size-1; i >= 0; i--)
326 <                if (o.equals(elementData[i]))
325 >            for (int i = end - 1; i >= start; i--) {
326 >                if (o.equals(es[i])) {
327                      return i;
328 +                }
329 +            }
330          }
331          return -1;
332      }
# Line 424 | Line 409 | public class ArrayList<E> extends Abstra
409          return (E) elementData[index];
410      }
411  
412 +    @SuppressWarnings("unchecked")
413 +    static <E> E elementAt(Object[] es, int index) {
414 +        return (E) es[index];
415 +    }
416 +
417      /**
418       * Returns the element at the specified position in this list.
419       *
# Line 497 | Line 487 | public class ArrayList<E> extends Abstra
487                           s - index);
488          elementData[index] = element;
489          size = s + 1;
490 +        // checkInvariants();
491      }
492  
493      /**
# Line 510 | Line 501 | public class ArrayList<E> extends Abstra
501       */
502      public E remove(int index) {
503          Objects.checkIndex(index, size);
504 +        final Object[] es = elementData;
505  
506 <        modCount++;
507 <        E oldValue = elementData(index);
516 <
517 <        int numMoved = size - index - 1;
518 <        if (numMoved > 0)
519 <            System.arraycopy(elementData, index+1, elementData, index,
520 <                             numMoved);
521 <        elementData[--size] = null; // clear to let GC do its work
506 >        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
507 >        fastRemove(es, index);
508  
509 +        // checkInvariants();
510          return oldValue;
511      }
512  
513      /**
514 +     * {@inheritDoc}
515 +     */
516 +    public boolean equals(Object o) {
517 +        if (o == this) {
518 +            return true;
519 +        }
520 +
521 +        if (!(o instanceof List)) {
522 +            return false;
523 +        }
524 +
525 +        final int expectedModCount = modCount;
526 +        // ArrayList can be subclassed and given arbitrary behavior, but we can
527 +        // still deal with the common case where o is ArrayList precisely
528 +        boolean equal = (o.getClass() == ArrayList.class)
529 +            ? equalsArrayList((ArrayList<?>) o)
530 +            : equalsRange((List<?>) o, 0, size);
531 +
532 +        checkForComodification(expectedModCount);
533 +        return equal;
534 +    }
535 +
536 +    boolean equalsRange(List<?> other, int from, int to) {
537 +        final Object[] es = elementData;
538 +        if (to > es.length) {
539 +            throw new ConcurrentModificationException();
540 +        }
541 +        var oit = other.iterator();
542 +        for (; from < to; from++) {
543 +            if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
544 +                return false;
545 +            }
546 +        }
547 +        return !oit.hasNext();
548 +    }
549 +
550 +    private boolean equalsArrayList(ArrayList<?> other) {
551 +        final int otherModCount = other.modCount;
552 +        final int s = size;
553 +        boolean equal;
554 +        if (equal = (s == other.size)) {
555 +            final Object[] otherEs = other.elementData;
556 +            final Object[] es = elementData;
557 +            if (s > es.length || s > otherEs.length) {
558 +                throw new ConcurrentModificationException();
559 +            }
560 +            for (int i = 0; i < s; i++) {
561 +                if (!Objects.equals(es[i], otherEs[i])) {
562 +                    equal = false;
563 +                    break;
564 +                }
565 +            }
566 +        }
567 +        other.checkForComodification(otherModCount);
568 +        return equal;
569 +    }
570 +
571 +    private void checkForComodification(final int expectedModCount) {
572 +        if (modCount != expectedModCount) {
573 +            throw new ConcurrentModificationException();
574 +        }
575 +    }
576 +
577 +    /**
578 +     * {@inheritDoc}
579 +     */
580 +    public int hashCode() {
581 +        int expectedModCount = modCount;
582 +        int hash = hashCodeRange(0, size);
583 +        checkForComodification(expectedModCount);
584 +        return hash;
585 +    }
586 +
587 +    int hashCodeRange(int from, int to) {
588 +        final Object[] es = elementData;
589 +        if (to > es.length) {
590 +            throw new ConcurrentModificationException();
591 +        }
592 +        int hashCode = 1;
593 +        for (int i = from; i < to; i++) {
594 +            Object e = es[i];
595 +            hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
596 +        }
597 +        return hashCode;
598 +    }
599 +
600 +    /**
601       * Removes the first occurrence of the specified element from this list,
602       * if it is present.  If the list does not contain the element, it is
603       * unchanged.  More formally, removes the element with the lowest index
# Line 537 | Line 611 | public class ArrayList<E> extends Abstra
611       * @return {@code true} if this list contained the specified element
612       */
613      public boolean remove(Object o) {
614 <        if (o == null) {
615 <            for (int index = 0; index < size; index++)
616 <                if (elementData[index] == null) {
617 <                    fastRemove(index);
618 <                    return true;
619 <                }
620 <        } else {
621 <            for (int index = 0; index < size; index++)
622 <                if (o.equals(elementData[index])) {
623 <                    fastRemove(index);
624 <                    return true;
625 <                }
614 >        final Object[] es = elementData;
615 >        final int size = this.size;
616 >        int i = 0;
617 >        found: {
618 >            if (o == null) {
619 >                for (; i < size; i++)
620 >                    if (es[i] == null)
621 >                        break found;
622 >            } else {
623 >                for (; i < size; i++)
624 >                    if (o.equals(es[i]))
625 >                        break found;
626 >            }
627 >            return false;
628          }
629 <        return false;
629 >        fastRemove(es, i);
630 >        return true;
631      }
632  
633 <    /*
633 >    /**
634       * Private remove method that skips bounds checking and does not
635       * return the value removed.
636       */
637 <    private void fastRemove(int index) {
637 >    private void fastRemove(Object[] es, int i) {
638          modCount++;
639 <        int numMoved = size - index - 1;
640 <        if (numMoved > 0)
641 <            System.arraycopy(elementData, index+1, elementData, index,
642 <                             numMoved);
566 <        elementData[--size] = null; // clear to let GC do its work
639 >        final int newSize;
640 >        if ((newSize = size - 1) > i)
641 >            System.arraycopy(es, i + 1, es, i, newSize - i);
642 >        es[size = newSize] = null;
643      }
644  
645      /**
# Line 572 | Line 648 | public class ArrayList<E> extends Abstra
648       */
649      public void clear() {
650          modCount++;
651 <
652 <        // clear to let GC do its work
653 <        for (int i = 0; i < size; i++)
578 <            elementData[i] = null;
579 <
580 <        size = 0;
651 >        final Object[] es = elementData;
652 >        for (int to = size, i = size = 0; i < to; i++)
653 >            es[i] = null;
654      }
655  
656      /**
# Line 605 | Line 678 | public class ArrayList<E> extends Abstra
678              elementData = grow(s + numNew);
679          System.arraycopy(a, 0, elementData, s, numNew);
680          size = s + numNew;
681 +        // checkInvariants();
682          return true;
683      }
684  
# Line 643 | Line 717 | public class ArrayList<E> extends Abstra
717                               numMoved);
718          System.arraycopy(a, 0, elementData, index, numNew);
719          size = s + numNew;
720 +        // checkInvariants();
721          return true;
722      }
723  
# Line 665 | Line 740 | public class ArrayList<E> extends Abstra
740                      outOfBoundsMsg(fromIndex, toIndex));
741          }
742          modCount++;
743 <        int numMoved = size - toIndex;
744 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
745 <                         numMoved);
746 <
747 <        // clear to let GC do its work
748 <        int newSize = size - (toIndex-fromIndex);
749 <        for (int i = newSize; i < size; i++) {
750 <            elementData[i] = null;
751 <        }
677 <        size = newSize;
743 >        shiftTailOverGap(elementData, fromIndex, toIndex);
744 >        // checkInvariants();
745 >    }
746 >
747 >    /** Erases the gap from lo to hi, by sliding down following elements. */
748 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
749 >        System.arraycopy(es, hi, es, lo, size - hi);
750 >        for (int to = size, i = (size -= hi - lo); i < to; i++)
751 >            es[i] = null;
752      }
753  
754      /**
# Line 717 | Line 791 | public class ArrayList<E> extends Abstra
791       * @see Collection#contains(Object)
792       */
793      public boolean removeAll(Collection<?> c) {
794 <        Objects.requireNonNull(c);
721 <        return batchRemove(c, false);
794 >        return batchRemove(c, false, 0, size);
795      }
796  
797      /**
# Line 738 | Line 811 | public class ArrayList<E> extends Abstra
811       * @see Collection#contains(Object)
812       */
813      public boolean retainAll(Collection<?> c) {
814 <        Objects.requireNonNull(c);
742 <        return batchRemove(c, true);
814 >        return batchRemove(c, true, 0, size);
815      }
816  
817 <    private boolean batchRemove(Collection<?> c, boolean complement) {
818 <        final Object[] elementData = this.elementData;
819 <        int r = 0, w = 0;
820 <        boolean modified = false;
817 >    boolean batchRemove(Collection<?> c, boolean complement,
818 >                        final int from, final int end) {
819 >        Objects.requireNonNull(c);
820 >        final Object[] es = elementData;
821 >        int r;
822 >        // Optimize for initial run of survivors
823 >        for (r = from;; r++) {
824 >            if (r == end)
825 >                return false;
826 >            if (c.contains(es[r]) != complement)
827 >                break;
828 >        }
829 >        int w = r++;
830          try {
831 <            for (; r < size; r++)
832 <                if (c.contains(elementData[r]) == complement)
833 <                    elementData[w++] = elementData[r];
834 <        } finally {
831 >            for (Object e; r < end; r++)
832 >                if (c.contains(e = es[r]) == complement)
833 >                    es[w++] = e;
834 >        } catch (Throwable ex) {
835              // Preserve behavioral compatibility with AbstractCollection,
836              // even if c.contains() throws.
837 <            if (r != size) {
838 <                System.arraycopy(elementData, r,
839 <                                 elementData, w,
840 <                                 size - r);
841 <                w += size - r;
842 <            }
762 <            if (w != size) {
763 <                // clear to let GC do its work
764 <                for (int i = w; i < size; i++)
765 <                    elementData[i] = null;
766 <                modCount += size - w;
767 <                size = w;
768 <                modified = true;
769 <            }
837 >            System.arraycopy(es, r, es, w, end - r);
838 >            w += end - r;
839 >            throw ex;
840 >        } finally {
841 >            modCount += end - w;
842 >            shiftTailOverGap(es, w, end);
843          }
844 <        return modified;
844 >        // checkInvariants();
845 >        return true;
846      }
847  
848      /**
849 <     * Save the state of the {@code ArrayList} instance to a stream (that
850 <     * is, serialize it).
849 >     * Saves the state of the {@code ArrayList} instance to a stream
850 >     * (that is, serializes it).
851       *
852 +     * @param s the stream
853 +     * @throws java.io.IOException if an I/O error occurs
854       * @serialData The length of the array backing the {@code ArrayList}
855       *             instance is emitted (int), followed by all of its elements
856       *             (each an {@code Object}) in the proper order.
857       */
858      private void writeObject(java.io.ObjectOutputStream s)
859 <        throws java.io.IOException{
859 >        throws java.io.IOException {
860          // Write out element count, and any hidden stuff
861          int expectedModCount = modCount;
862          s.defaultWriteObject();
863  
864 <        // Write out size as capacity for behavioural compatibility with clone()
864 >        // Write out size as capacity for behavioral compatibility with clone()
865          s.writeInt(size);
866  
867          // Write out all elements in the proper order.
# Line 799 | Line 875 | public class ArrayList<E> extends Abstra
875      }
876  
877      /**
878 <     * Reconstitute the {@code ArrayList} instance from a stream (that is,
879 <     * deserialize it).
878 >     * Reconstitutes the {@code ArrayList} instance from a stream (that is,
879 >     * deserializes it).
880 >     * @param s the stream
881 >     * @throws ClassNotFoundException if the class of a serialized object
882 >     *         could not be found
883 >     * @throws java.io.IOException if an I/O error occurs
884       */
885      private void readObject(java.io.ObjectInputStream s)
886          throws java.io.IOException, ClassNotFoundException {
# Line 813 | Line 893 | public class ArrayList<E> extends Abstra
893  
894          if (size > 0) {
895              // like clone(), allocate array based upon size not capacity
896 +            jsr166.Platform.checkArray(s, Object[].class, size);
897              Object[] elements = new Object[size];
898  
899              // Read in all elements in the proper order.
# Line 912 | Line 993 | public class ArrayList<E> extends Abstra
993          }
994  
995          @Override
996 <        @SuppressWarnings("unchecked")
997 <        public void forEachRemaining(Consumer<? super E> consumer) {
917 <            Objects.requireNonNull(consumer);
996 >        public void forEachRemaining(Consumer<? super E> action) {
997 >            Objects.requireNonNull(action);
998              final int size = ArrayList.this.size;
999              int i = cursor;
1000 <            if (i >= size) {
1001 <                return;
1002 <            }
1003 <            final Object[] elementData = ArrayList.this.elementData;
1004 <            if (i >= elementData.length) {
1005 <                throw new ConcurrentModificationException();
1006 <            }
1007 <            while (i != size && modCount == expectedModCount) {
1008 <                consumer.accept((E) elementData[i++]);
1000 >            if (i < size) {
1001 >                final Object[] es = elementData;
1002 >                if (i >= es.length)
1003 >                    throw new ConcurrentModificationException();
1004 >                for (; i < size && modCount == expectedModCount; i++)
1005 >                    action.accept(elementAt(es, i));
1006 >                // update once at end to reduce heap write traffic
1007 >                cursor = i;
1008 >                lastRet = i - 1;
1009 >                checkForComodification();
1010              }
930            // update once at end of iteration to reduce heap write traffic
931            cursor = i;
932            lastRet = i - 1;
933            checkForComodification();
1011          }
1012  
1013          final void checkForComodification() {
# Line 1117 | Line 1194 | public class ArrayList<E> extends Abstra
1194              return true;
1195          }
1196  
1197 +        public void replaceAll(UnaryOperator<E> operator) {
1198 +            root.replaceAllRange(operator, offset, offset + size);
1199 +        }
1200 +
1201 +        public boolean removeAll(Collection<?> c) {
1202 +            return batchRemove(c, false);
1203 +        }
1204 +
1205 +        public boolean retainAll(Collection<?> c) {
1206 +            return batchRemove(c, true);
1207 +        }
1208 +
1209 +        private boolean batchRemove(Collection<?> c, boolean complement) {
1210 +            checkForComodification();
1211 +            int oldSize = root.size;
1212 +            boolean modified =
1213 +                root.batchRemove(c, complement, offset, offset + size);
1214 +            if (modified)
1215 +                updateSizeAndModCount(root.size - oldSize);
1216 +            return modified;
1217 +        }
1218 +
1219 +        public boolean removeIf(Predicate<? super E> filter) {
1220 +            checkForComodification();
1221 +            int oldSize = root.size;
1222 +            boolean modified = root.removeIf(filter, offset, offset + size);
1223 +            if (modified)
1224 +                updateSizeAndModCount(root.size - oldSize);
1225 +            return modified;
1226 +        }
1227 +
1228 +        public Object[] toArray() {
1229 +            checkForComodification();
1230 +            return Arrays.copyOfRange(root.elementData, offset, offset + size);
1231 +        }
1232 +
1233 +        @SuppressWarnings("unchecked")
1234 +        public <T> T[] toArray(T[] a) {
1235 +            checkForComodification();
1236 +            if (a.length < size)
1237 +                return (T[]) Arrays.copyOfRange(
1238 +                        root.elementData, offset, offset + size, a.getClass());
1239 +            System.arraycopy(root.elementData, offset, a, 0, size);
1240 +            if (a.length > size)
1241 +                a[size] = null;
1242 +            return a;
1243 +        }
1244 +
1245 +        public boolean equals(Object o) {
1246 +            if (o == this) {
1247 +                return true;
1248 +            }
1249 +
1250 +            if (!(o instanceof List)) {
1251 +                return false;
1252 +            }
1253 +
1254 +            boolean equal = root.equalsRange((List<?>)o, offset, offset + size);
1255 +            checkForComodification();
1256 +            return equal;
1257 +        }
1258 +
1259 +        public int hashCode() {
1260 +            int hash = root.hashCodeRange(offset, offset + size);
1261 +            checkForComodification();
1262 +            return hash;
1263 +        }
1264 +
1265 +        public int indexOf(Object o) {
1266 +            int index = root.indexOfRange(o, offset, offset + size);
1267 +            checkForComodification();
1268 +            return index >= 0 ? index - offset : -1;
1269 +        }
1270 +
1271 +        public int lastIndexOf(Object o) {
1272 +            int index = root.lastIndexOfRange(o, offset, offset + size);
1273 +            checkForComodification();
1274 +            return index >= 0 ? index - offset : -1;
1275 +        }
1276 +
1277 +        public boolean contains(Object o) {
1278 +            return indexOf(o) >= 0;
1279 +        }
1280 +
1281          public Iterator<E> iterator() {
1282              return listIterator();
1283          }
# Line 1164 | Line 1325 | public class ArrayList<E> extends Abstra
1325                      return (E) elementData[offset + (lastRet = i)];
1326                  }
1327  
1328 <                @SuppressWarnings("unchecked")
1329 <                public void forEachRemaining(Consumer<? super E> consumer) {
1169 <                    Objects.requireNonNull(consumer);
1328 >                public void forEachRemaining(Consumer<? super E> action) {
1329 >                    Objects.requireNonNull(action);
1330                      final int size = SubList.this.size;
1331                      int i = cursor;
1332 <                    if (i >= size) {
1333 <                        return;
1334 <                    }
1335 <                    final Object[] elementData = root.elementData;
1336 <                    if (offset + i >= elementData.length) {
1337 <                        throw new ConcurrentModificationException();
1338 <                    }
1339 <                    while (i != size && modCount == expectedModCount) {
1340 <                        consumer.accept((E) elementData[offset + (i++)]);
1332 >                    if (i < size) {
1333 >                        final Object[] es = root.elementData;
1334 >                        if (offset + i >= es.length)
1335 >                            throw new ConcurrentModificationException();
1336 >                        for (; i < size && modCount == expectedModCount; i++)
1337 >                            action.accept(elementAt(es, offset + i));
1338 >                        // update once at end to reduce heap write traffic
1339 >                        cursor = i;
1340 >                        lastRet = i - 1;
1341 >                        checkForComodification();
1342                      }
1182                    // update once at end of iteration to reduce heap write traffic
1183                    lastRet = cursor = i;
1184                    checkForComodification();
1343                  }
1344  
1345                  public int nextIndex() {
# Line 1271 | Line 1429 | public class ArrayList<E> extends Abstra
1429          public Spliterator<E> spliterator() {
1430              checkForComodification();
1431  
1432 <            // ArrayListSpliterator is not used because late-binding logic
1433 <            // is different here
1276 <            return new Spliterator<>() {
1432 >            // ArrayListSpliterator not used here due to late-binding
1433 >            return new Spliterator<E>() {
1434                  private int index = offset; // current index, modified on advance/split
1435                  private int fence = -1; // -1 until used; then one past last index
1436                  private int expectedModCount; // initialized when fence set
# Line 1287 | Line 1444 | public class ArrayList<E> extends Abstra
1444                      return hi;
1445                  }
1446  
1447 <                public ArrayListSpliterator<E> trySplit() {
1447 >                public ArrayList<E>.ArrayListSpliterator trySplit() {
1448                      int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1449 <                    // ArrayListSpliterator could be used here as the source is already bound
1449 >                    // ArrayListSpliterator can be used here as the source is already bound
1450                      return (lo >= mid) ? null : // divide range in half unless too small
1451 <                        new ArrayListSpliterator<>(root, lo, index = mid,
1295 <                                                   expectedModCount);
1451 >                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1452                  }
1453  
1454                  public boolean tryAdvance(Consumer<? super E> action) {
# Line 1334 | Line 1490 | public class ArrayList<E> extends Abstra
1490                  }
1491  
1492                  public long estimateSize() {
1493 <                    return (long) (getFence() - index);
1493 >                    return getFence() - index;
1494                  }
1495  
1496                  public int characteristics() {
# Line 1344 | Line 1500 | public class ArrayList<E> extends Abstra
1500          }
1501      }
1502  
1503 +    /**
1504 +     * @throws NullPointerException {@inheritDoc}
1505 +     */
1506      @Override
1507      public void forEach(Consumer<? super E> action) {
1508          Objects.requireNonNull(action);
1509          final int expectedModCount = modCount;
1510 <        @SuppressWarnings("unchecked")
1352 <        final E[] elementData = (E[]) this.elementData;
1510 >        final Object[] es = elementData;
1511          final int size = this.size;
1512 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1513 <            action.accept(elementData[i]);
1514 <        }
1357 <        if (modCount != expectedModCount) {
1512 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1513 >            action.accept(elementAt(es, i));
1514 >        if (modCount != expectedModCount)
1515              throw new ConcurrentModificationException();
1359        }
1516      }
1517  
1518      /**
# Line 1374 | Line 1530 | public class ArrayList<E> extends Abstra
1530       */
1531      @Override
1532      public Spliterator<E> spliterator() {
1533 <        return new ArrayListSpliterator<>(this, 0, -1, 0);
1533 >        return new ArrayListSpliterator(0, -1, 0);
1534      }
1535  
1536      /** Index-based split-by-two, lazily initialized Spliterator */
1537 <    static final class ArrayListSpliterator<E> implements Spliterator<E> {
1537 >    final class ArrayListSpliterator implements Spliterator<E> {
1538  
1539          /*
1540           * If ArrayLists were immutable, or structurally immutable (no
# Line 1412 | Line 1568 | public class ArrayList<E> extends Abstra
1568           * these streamlinings.
1569           */
1570  
1415        private final ArrayList<E> list;
1571          private int index; // current index, modified on advance/split
1572          private int fence; // -1 until used; then one past last index
1573          private int expectedModCount; // initialized when fence set
1574  
1575 <        /** Create new spliterator covering the given  range */
1576 <        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
1422 <                             int expectedModCount) {
1423 <            this.list = list; // OK if null unless traversed
1575 >        /** Creates new spliterator covering the given range. */
1576 >        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1577              this.index = origin;
1578              this.fence = fence;
1579              this.expectedModCount = expectedModCount;
# Line 1428 | Line 1581 | public class ArrayList<E> extends Abstra
1581  
1582          private int getFence() { // initialize fence to size on first use
1583              int hi; // (a specialized variant appears in method forEach)
1431            ArrayList<E> lst;
1584              if ((hi = fence) < 0) {
1585 <                if ((lst = list) == null)
1586 <                    hi = fence = 0;
1435 <                else {
1436 <                    expectedModCount = lst.modCount;
1437 <                    hi = fence = lst.size;
1438 <                }
1585 >                expectedModCount = modCount;
1586 >                hi = fence = size;
1587              }
1588              return hi;
1589          }
1590  
1591 <        public ArrayListSpliterator<E> trySplit() {
1591 >        public ArrayListSpliterator trySplit() {
1592              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1593              return (lo >= mid) ? null : // divide range in half unless too small
1594 <                new ArrayListSpliterator<>(list, lo, index = mid,
1447 <                                           expectedModCount);
1594 >                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1595          }
1596  
1597          public boolean tryAdvance(Consumer<? super E> action) {
# Line 1453 | Line 1600 | public class ArrayList<E> extends Abstra
1600              int hi = getFence(), i = index;
1601              if (i < hi) {
1602                  index = i + 1;
1603 <                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
1603 >                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1604                  action.accept(e);
1605 <                if (list.modCount != expectedModCount)
1605 >                if (modCount != expectedModCount)
1606                      throw new ConcurrentModificationException();
1607                  return true;
1608              }
# Line 1464 | Line 1611 | public class ArrayList<E> extends Abstra
1611  
1612          public void forEachRemaining(Consumer<? super E> action) {
1613              int i, hi, mc; // hoist accesses and checks from loop
1614 <            ArrayList<E> lst; Object[] a;
1614 >            Object[] a;
1615              if (action == null)
1616                  throw new NullPointerException();
1617 <            if ((lst = list) != null && (a = lst.elementData) != null) {
1617 >            if ((a = elementData) != null) {
1618                  if ((hi = fence) < 0) {
1619 <                    mc = lst.modCount;
1620 <                    hi = lst.size;
1619 >                    mc = modCount;
1620 >                    hi = size;
1621                  }
1622                  else
1623                      mc = expectedModCount;
# Line 1479 | Line 1626 | public class ArrayList<E> extends Abstra
1626                          @SuppressWarnings("unchecked") E e = (E) a[i];
1627                          action.accept(e);
1628                      }
1629 <                    if (lst.modCount == mc)
1629 >                    if (modCount == mc)
1630                          return;
1631                  }
1632              }
# Line 1487 | Line 1634 | public class ArrayList<E> extends Abstra
1634          }
1635  
1636          public long estimateSize() {
1637 <            return (long) (getFence() - index);
1637 >            return getFence() - index;
1638          }
1639  
1640          public int characteristics() {
# Line 1495 | Line 1642 | public class ArrayList<E> extends Abstra
1642          }
1643      }
1644  
1645 +    // A tiny bit set implementation
1646 +
1647 +    private static long[] nBits(int n) {
1648 +        return new long[((n - 1) >> 6) + 1];
1649 +    }
1650 +    private static void setBit(long[] bits, int i) {
1651 +        bits[i >> 6] |= 1L << i;
1652 +    }
1653 +    private static boolean isClear(long[] bits, int i) {
1654 +        return (bits[i >> 6] & (1L << i)) == 0;
1655 +    }
1656 +
1657 +    /**
1658 +     * @throws NullPointerException {@inheritDoc}
1659 +     */
1660      @Override
1661      public boolean removeIf(Predicate<? super E> filter) {
1662 +        return removeIf(filter, 0, size);
1663 +    }
1664 +
1665 +    /**
1666 +     * Removes all elements satisfying the given predicate, from index
1667 +     * i (inclusive) to index end (exclusive).
1668 +     */
1669 +    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1670          Objects.requireNonNull(filter);
1671 <        final int expectedModCount = modCount;
1672 <        final Object[] elementData = this.elementData;
1673 <        int r = 0, w = 0, remaining = size, deleted = 0;
1674 <        try {
1675 <            for (; remaining > 0; remaining--, r++) {
1676 <                @SuppressWarnings("unchecked") E e = (E) elementData[r];
1677 <                if (filter.test(e))
1678 <                    deleted++;
1679 <                else {
1680 <                    if (r != w)
1681 <                        elementData[w] = e;
1682 <                    w++;
1683 <                }
1684 <            }
1671 >        int expectedModCount = modCount;
1672 >        final Object[] es = elementData;
1673 >        // Optimize for initial run of survivors
1674 >        for (; i < end && !filter.test(elementAt(es, i)); i++)
1675 >            ;
1676 >        // Tolerate predicates that reentrantly access the collection for
1677 >        // read (but writers still get CME), so traverse once to find
1678 >        // elements to delete, a second pass to physically expunge.
1679 >        if (i < end) {
1680 >            final int beg = i;
1681 >            final long[] deathRow = nBits(end - beg);
1682 >            deathRow[0] = 1L;   // set bit 0
1683 >            for (i = beg + 1; i < end; i++)
1684 >                if (filter.test(elementAt(es, i)))
1685 >                    setBit(deathRow, i - beg);
1686              if (modCount != expectedModCount)
1687                  throw new ConcurrentModificationException();
1688 <            return deleted > 0;
1689 <        } catch (Throwable ex) {
1690 <            if (deleted > 0)
1691 <                for (; remaining > 0; remaining--, r++, w++)
1692 <                    elementData[w] = elementData[r];
1693 <            throw ex;
1694 <        } finally {
1695 <            if (deleted > 0) {
1696 <                modCount++;
1697 <                size -= deleted;
1698 <                while (--deleted >= 0)
1699 <                    elementData[w++] = null;
1700 <            }
1688 >            modCount++;
1689 >            int w = beg;
1690 >            for (i = beg; i < end; i++)
1691 >                if (isClear(deathRow, i - beg))
1692 >                    es[w++] = es[i];
1693 >            shiftTailOverGap(es, w, end);
1694 >            // checkInvariants();
1695 >            return true;
1696 >        } else {
1697 >            if (modCount != expectedModCount)
1698 >                throw new ConcurrentModificationException();
1699 >            // checkInvariants();
1700 >            return false;
1701          }
1702      }
1703  
1704      @Override
1534    @SuppressWarnings("unchecked")
1705      public void replaceAll(UnaryOperator<E> operator) {
1706 +        replaceAllRange(operator, 0, size);
1707 +        // TODO(8203662): remove increment of modCount from ...
1708 +        modCount++;
1709 +    }
1710 +
1711 +    private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
1712          Objects.requireNonNull(operator);
1713          final int expectedModCount = modCount;
1714 <        final int size = this.size;
1715 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1716 <            elementData[i] = operator.apply((E) elementData[i]);
1717 <        }
1542 <        if (modCount != expectedModCount) {
1714 >        final Object[] es = elementData;
1715 >        for (; modCount == expectedModCount && i < end; i++)
1716 >            es[i] = operator.apply(elementAt(es, i));
1717 >        if (modCount != expectedModCount)
1718              throw new ConcurrentModificationException();
1719 <        }
1545 <        modCount++;
1719 >        // checkInvariants();
1720      }
1721  
1722      @Override
# Line 1550 | Line 1724 | public class ArrayList<E> extends Abstra
1724      public void sort(Comparator<? super E> c) {
1725          final int expectedModCount = modCount;
1726          Arrays.sort((E[]) elementData, 0, size, c);
1727 <        if (modCount != expectedModCount) {
1727 >        if (modCount != expectedModCount)
1728              throw new ConcurrentModificationException();
1555        }
1729          modCount++;
1730 +        // checkInvariants();
1731 +    }
1732 +
1733 +    void checkInvariants() {
1734 +        // assert size >= 0;
1735 +        // assert size == elementData.length || elementData[size] == null;
1736      }
1737   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines