Difference between various Array copy methods

Viewed 13724

What is the difference between

  • System.arraycopy(),
  • clone()
  • manual copying by iterating through the elements
  • Arrays.copyOf()
  • and just doing arraynew = arrayold?
4 Answers

There are answers but not a complete one.

The options considered are

  • Arrays.copyOf()
  • System.arraycopy()

Below is the java implementation of Arrays.copyOf()

public static double[] More ...copyOf(double[] original, int newLength) {
        double[] copy = new double[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
   }

As you can see copyOf uses System.arraycopy internally.

  • If you already have an array created use System.arraycopy() to copy
  • If you need the result in a new array use Arrays.copyOf() to copy

Note: There is no point in comparing the speed obviously because their functionalities differ.

Related