Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between various Array copy methods

Tags:

What is the difference between

  • System.arraycopy(),
  • clone()
  • manual copying by iterating through the elements
  • Arrays.copyOf()
  • and just doing arraynew = arrayold?
like image 588
unj2 Avatar asked Nov 08 '09 17:11

unj2


2 Answers

  • System.arraycopy() uses JNI (Java Native Interface) to copy an array (or parts of it), so it is blazingly fast, as you can confirm here;
  • clone() creates a new array with the same characteristics as the old array, i.e., same size, same type, and same contents. Refer to here for some examples of clone in action;
  • manual copying is, well, manual copying. There isn't much to say about this method, except that many people have found it to be the most performant.
  • arraynew = arrayold doesn't copy the array; it just points arraynew to the memory address of arrayold or, in other words, you are simply assigning a reference to the old array.
like image 92
João Silva Avatar answered Sep 30 '22 15:09

João Silva


  • System.arraycopy() copies data from one existing array into another one and depending on the arguments only copies parts of it.
  • clone() allocates a new array that has the same type and size than the original and ensures that it has the same content.
  • manual copying usually does pretty much the same thing than System.arraycopy(), but is more code and therefore a bigger source for errors
  • arraynew = arrayold only copies the reference to the array to a new variable and doesn't influence the array itself

There is one more useful option:

Arrays.copyOf() can be used to create a copy of another array with a different size. This means that the new array can be bigger or larger than the original array and the content of the common size will be that of the source. There's even a version that makes it possible to create an array of a different type, and a version where you can specify a range of elements to copy (Array.copyOfRange()).

Note that all of those methods make shallow copies. That means that only the references stored in the arrays are copied and the referenced objects are not duplicated.

like image 32
Joachim Sauer Avatar answered Sep 30 '22 14:09

Joachim Sauer