When copying an entire array, I've often seen people write:
int[] dest = new int[orig.length];
System.arraycopy(orig, 0, dest, 0, orig.length);
But it seems to me there is no reason to favor this over:
int[] dest = orig.clone();
They're both shallow copies anyway. Probably these folks just don't realize that clone
exists. So is there any reason not to use clone
?
clone()
makes a distinct copy of the first array with its own reference.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.