Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8257475

reduce array copying in various Collections' copy constructors

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • tbd
    • None
    • core-libs
    • None

      Consider new ArrayList<E>(Collection<E> arg). This calls arg.toArray() and makes a defensive copy of it for use use as the internal array to the ArrayList. This copy is necessary in case the arg's toArray() implementation produces an array whose class is something other than Object[].class or if it retains a reference to the returned array. (Both of these are spec violations, but they're unenforceable.)

      The JDK collections implementations are implemented correctly, so in most cases the defensive copy is unnecessary. In some cases the copy is skipped if the class of arg is ArrayList.class; this handles a few cases but there are many other cases where the toArray() method is known to be correct. However, this is difficult to ascertain at the point where toArray() is called.

      A mechanism should be added so that the caller of arg.toArray() can determine whether the implementation is correct and thus can avoid making the defensive copy.

            smarks Stuart Marks
            smarks Stuart Marks
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: