Is there an equivalent to memcpy() in Java?

Tags: ,



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?

Answer

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));


Source: stackoverflow