34

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?

JavaRocky
  • 19,203
  • 31
  • 89
  • 110

4 Answers4

47

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 method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone 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.

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

MarMi00
  • 5
  • 3
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • Nice. I swore `.clone` didn't work for arrays; I would've said `arraycopy` [like TofuBeer](http://stackoverflow.com/questions/3208899/how-do-i-clone-a-java-byte-array/3208918#3208918) – Michael Mrozek Jul 09 '10 at 00:04
  • 1
    I just like arraycopy because I don't like clone in general - broken by design :-) – TofuBeer Jul 09 '10 at 00:06
  • 1
    @TofuBeer: yes, `clone` generally is indeed broken, but Bloch claims that Doug Lea makes an exception for arrays (http://www.artima.com/intv/bloch13.html) – polygenelubricants Jul 09 '10 at 00:08
10

System.arraycopy(src, 0, dst, 0, src.length);

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
9

It's easy, and it's a great idea to do it.

byte[] copy = arr.clone();

Note that the return type of the clone() method of arrays is the type of the array, so no cast is required.

erickson
  • 265,237
  • 58
  • 395
  • 493
4

In order to avoid a possible Null Pointer Exception I use the following syntax:

byte[] copy = (arr == null) ? null : arr.clone();
holmis83
  • 15,922
  • 5
  • 82
  • 83
Cooper
  • 41
  • 1