If we want to copy an array, we may use either system.arraycopy () or arrays.copyof (). Here, we will use a relatively simple example to illustrate the difference between the two.
1. Sample code:
System.arraycopy ()
int [] arr = {1,2,3,4,5intnewint[ Ten 015); // 5 is the length to copy System. out. println (arrays.tostring (copied));
Operation Result:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
Arrays.copyof ()
int // The length of the new array = arrays.copyof (arr, 3); System.out.println (arrays.tostring (copied));
Operation Result:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]
2. The main difference between the two
The difference is that arrays.copyof () is not just a copy of an element in an array, but a new array object is created when the element is copied. Instead, system.arraycopy only copies the array elements that already exist.
If we have seen the source of arrays.copyof (), we will know that the bottom of the method is called the system.arraycopyof () method.
Public Static int [] copyOf (intint newlength) { intnewint[newlength] ; 0, copy, 0, Math.min (Original.length, newlength)); return copy;}
The difference between system.arraycopy () and arrays.copyof () in Java-java