1. Shallow copy instructions
Copy all the attributes of the member variables in the prototype object that are value types to the cloned object, and also copy the reference addresses of the member variables in the prototype object that are reference types. Copied to the clone object, that is, if a member variable in the prototype object is a reference object, the address of this reference object is shared between the prototype object and the clone object. Simply put, a shallow copy will only copy the prototype object, but not the object it refers to.
2.Arrays.copyOf() copy
creates a new array (that is, allocates a new memory space), and then calls System.arraycopy( ) copies the contents, assigns to the new array, and returns the new array.
3. Example
public static byte[] copyOfRange(byte[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); byte[] copy = new byte[newLength]; System.arraycopy(original, from, copy, 0,Math.min(original.length - from, newLength)); return copy; }
In fact, it calls System.arraycopy, so it must be a shallow copy.
The above is the detailed content of How to implement shallow copy using Java's Arrays.copyOf?. For more information, please follow other related articles on the PHP Chinese website!