I have a byte array which i want to copy/clone to avoid calling code from modifying my internal representation.
How do I clone a java byte array?
copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.
Java allows you to copy arrays using either direct copy method provided by java. util or System class. It also provides a clone method that is used to clone an entire array.
The copyOfRange() method is used to copy the elements of the specified range of the original array into clone array. The syntax of the copyOfRange() method is as follows: public static int[] copyOfRange(int[] original, int from, int to)
JLS 6.4.5 The Members of an Array Type
The members of an array type are all of the following:
- The
public final field length
, which contains the number of components of the array (length may be positive or zero).- The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of the clone method of an array typeT[]
isT[]
.- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Thus:
byte[] original = ...; byte[] copy = original.clone();
Note that for array of reference types, clone()
is essentially a shallow copy.
Also, Java doesn't have multidimensional arrays; it has array of arrays. Thus, a byte[][]
is an Object[]
, and is also subject to shallow copy.
Note that clone()
returns a new array object. If you simply want to copy the values from one array to an already existing array, you can use e.g. System.arraycopy
.
There's also java.util.Arrays.copyOf
that allows you to create a copy with a different length (either truncating or padding).
System.arraycopy(src, 0, dst, 0, src.length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With