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.45 by jsr166, Wed Nov 30 03:31:47 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 218 | Line 220 | public class ArrayList<E> extends Abstra
220      }
221  
222      /**
221     * The maximum size of array to allocate (unless necessary).
222     * Some VMs reserve some header words in an array.
223     * Attempts to allocate larger arrays may result in
224     * OutOfMemoryError: Requested array size exceeds VM limit
225     */
226    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
227
228    /**
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 233 | 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 242 | Line 243 | public class ArrayList<E> extends Abstra
243      }
244  
245      /**
245     * Returns a capacity at least as large as the given minimum capacity.
246     * Returns the current capacity increased by 50% if that suffices.
247     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
248     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
249     *
250     * @param minCapacity the desired minimum capacity
251     * @throws OutOfMemoryError if minCapacity is less than zero
252     */
253    private int newCapacity(int minCapacity) {
254        // overflow-conscious code
255        int oldCapacity = elementData.length;
256        int newCapacity = oldCapacity + (oldCapacity >> 1);
257        if (newCapacity - minCapacity <= 0) {
258            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
259                return Math.max(DEFAULT_CAPACITY, minCapacity);
260            if (minCapacity < 0) // overflow
261                throw new OutOfMemoryError();
262            return minCapacity;
263        }
264        return (newCapacity - MAX_ARRAY_SIZE <= 0)
265            ? newCapacity
266            : hugeCapacity(minCapacity);
267    }
268
269    private static int hugeCapacity(int minCapacity) {
270        if (minCapacity < 0) // overflow
271            throw new OutOfMemoryError();
272        return (minCapacity > MAX_ARRAY_SIZE)
273            ? Integer.MAX_VALUE
274            : MAX_ARRAY_SIZE;
275    }
276
277    /**
246       * Returns the number of elements in this list.
247       *
248       * @return the number of elements in this list
# Line 313 | 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 333 | 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 515 | 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);
521 <
522 <        int numMoved = size - index - 1;
523 <        if (numMoved > 0)
524 <            System.arraycopy(elementData, index+1, elementData, index,
525 <                             numMoved);
526 <        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 543 | 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      /**
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);
572 <        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 578 | Line 648 | public class ArrayList<E> extends Abstra
648       */
649      public void clear() {
650          modCount++;
651 <        Arrays.fill(elementData, 0, size, null);
652 <        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 669 | Line 740 | public class ArrayList<E> extends Abstra
740                      outOfBoundsMsg(fromIndex, toIndex));
741          }
742          modCount++;
743 <        final Object[] es = elementData;
673 <        final int oldSize = size;
674 <        System.arraycopy(es, toIndex, es, fromIndex, oldSize - toIndex);
675 <        Arrays.fill(es, size -= (toIndex - fromIndex), oldSize, null);
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      /**
755       * A version of rangeCheck used by add and addAll.
756       */
# Line 743 | Line 818 | public class ArrayList<E> extends Abstra
818                          final int from, final int end) {
819          Objects.requireNonNull(c);
820          final Object[] es = elementData;
746        final boolean modified;
821          int r;
822          // Optimize for initial run of survivors
823 <        for (r = from; r < end && c.contains(es[r]) == complement; r++)
824 <            ;
825 <        if (modified = (r < end)) {
826 <            int w = r++;
827 <            try {
828 <                for (Object e; r < end; r++)
829 <                    if (c.contains(e = es[r]) == complement)
830 <                        es[w++] = e;
831 <            } catch (Throwable ex) {
832 <                // Preserve behavioral compatibility with AbstractCollection,
833 <                // even if c.contains() throws.
834 <                System.arraycopy(es, r, es, w, end - r);
835 <                w += end - r;
836 <                throw ex;
837 <            } finally {
838 <                final int oldSize = size, deleted = end - w;
839 <                modCount += deleted;
840 <                System.arraycopy(es, end, es, w, oldSize - end);
841 <                Arrays.fill(es, size -= deleted, oldSize, null);
842 <            }
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 (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 >            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          // checkInvariants();
845 <        return modified;
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 1113 | 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          }
# Line 1140 | Line 1225 | public class ArrayList<E> extends Abstra
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 1362 | 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);
# Line 1431 | Line 1572 | public class ArrayList<E> extends Abstra
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 */
1575 >        /** Creates new spliterator covering the given range. */
1576          ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1577              this.index = origin;
1578              this.fence = fence;
# Line 1513 | Line 1654 | public class ArrayList<E> extends Abstra
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);
# Line 1541 | Line 1685 | public class ArrayList<E> extends Abstra
1685                      setBit(deathRow, i - beg);
1686              if (modCount != expectedModCount)
1687                  throw new ConcurrentModificationException();
1544            expectedModCount++;
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 <            final int oldSize = size;
1551 <            System.arraycopy(es, end, es, w, oldSize - end);
1552 <            Arrays.fill(es, size -= (end - w), oldSize, null);
1693 >            shiftTailOverGap(es, w, end);
1694              // checkInvariants();
1695              return true;
1696          } else {
# Line 1562 | Line 1703 | public class ArrayList<E> extends Abstra
1703  
1704      @Override
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 Object[] es = elementData;
1715 <        final int size = this.size;
1569 <        for (int i = 0; modCount == expectedModCount && i < size; i++)
1715 >        for (; modCount == expectedModCount && i < end; i++)
1716              es[i] = operator.apply(elementAt(es, i));
1717          if (modCount != expectedModCount)
1718              throw new ConcurrentModificationException();
1573        modCount++;
1719          // checkInvariants();
1720      }
1721  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines