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

Arrays util for creating trailing copies

XMLWordPrintable

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

      The java.util.Arrays class has the copyOf method, which can be used to quickly create a copy of a given array. The length parameter of this method allows easily extending or truncating the returned copy. For example:

          String[] arr = { "B", "C", "D" };
          String[] copy1 = Arrays.copyOf(arr, arr.length + 1);
          copy1[copy1.length - 1] = "E"; // extend array by one element
          String[] copy2 = Arrays.copyOf(arr, arr.length - 1); // drop last element

      However, this only allows a client to extend or truncate at the _end_ of the array. So, e.g. if a client wants to insert extra elements at the start of the array, they need to fall back to using System.arraycopy:

          String[] arr = { "B", "C", "D" };
          String[] copy = new String[arr.length + 1];
          copy[0] = "A";
          System.arraycopy(arr, 0, copy, 1, arr.length);

      It would be nice if there was a util method in Arrays that allowed extending or truncating at the _start_ of an array as well. e.g.:

          String[] arr = { "B", "C", "D" };
          String[] copy1 = Arrays.copyOfTrailing(arr, arr.length + 1);
          copy1[0] = "A"; // extend
          String[] copy2 = Arrays.copyOfTrailing(arr, arr.length - 1); // truncate

      This is a bit shorter, and avoids users having to manually use System.arraycopy, which is a quite low-level API.

            smarks Stuart Marks
            jvernee Jorn Vernee
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: