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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Thus:
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 anObject[], and is also subject to shallow copy.See also
Related questions
Other options
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(jdk 1.0+).There’s also
java.util.Arrays.copyOf (jdk 1.6+) that allows you to create a copy with a different length (either truncating or padding).Related questions