tags:

views:

338

answers:

5

I have a byte[] and would like to copy it into another byte[]. Maybe I am showing my simple 'C' background here, but is there an equivalent to memcpy() on byte arrays in Java?

+16  A: 

You might try System.arraycopy or make use of array functions in the Arrays class like java.util.Arrays.copyOf. Both should give you native performance under the hood.

Arrays.copyOf is probably favourable for readability, but was only introduced in java 1.6.

 byte[] src = {1, 2, 3, 4};
 byte[] dst = Arrays.copyOf(src, src.length);
 System.out.println(Arrays.toString(dst));
Tom
I think the second option is more "logical". I never understood why System.arraycopy() is where is, one of the clumsiest possible locations.
Sinuhe
@Sinuhe - it is there for historical reasons.
Stephen C
+1  A: 

You can use System.arraycopy

Artem Barger
+4  A: 

You can use System.arrayCopy. It copies elements from a source array to a destination array. The Sun implementation uses hand-optimized assembler, so this is fast.

mdma
+8  A: 

Use System.arraycopy()

System.arraycopy(sourceArray, 
                 sourceStartIndex,
                 targetArray,
                 targetStartIndex,
                 length);

Example,

      String[] source = { "alpha", "beta", "gamma" };
      String[] target = new String[source.length];
      System.arraycopy(source, 0, target, 0, source.length);


or use Arrays.copyOf()
Example,

target = Arrays.copyOf(source, length);

java.util.Arrays.copyOf(byte[] source, int length) was added in JDK 1.6.
The copyOf() method uses System.arrayCopy() to make a copy of the array, but is more flexible than clone() since you can make copies of parts of an array.

Zaki
+1 for the examples.
Donal Fellows
+2  A: 

If you just want an exact copy of a one-dimensional array, use clone().

byte[] array = { 0x0A, 0x01 };
byte[] copy = array.clone();

For other array copy operations, use System.arrayCopy/Arrays.copyOf as Tom suggests.

In general, clone should be avoided, but this is an exception to the rule.

McDowell