Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to memcpy() in Java?

Tags:

java

bytearray

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?

like image 232
simon Avatar asked Jul 25 '10 12:07

simon


People also ask

What is System Arraycopy in Java?

arraycopy() method copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest.

What can you do with arrays in Java?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.


2 Answers

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.

like image 99
Zaki Avatar answered Sep 19 '22 08:09

Zaki


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)); 
like image 35
Tom Avatar answered Sep 19 '22 08:09

Tom