Is there an equivalent to memcpy() in Java?

Viewed 112576

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?

9 Answers

When you are using JDK 1.5+ You should use

System.arraycopy()

Instead of

Arrays.copyOfRange()

Beacuse Arrays.copyOfRange() wasn't added until JDK 1.6.So you might get

Java - “Cannot Find Symbol” error

when calling Arrays.copyOfRange in that version of JDK.

Use byteBufferViewVarHandle or byteArrayViewVarHandle.

This will let you copy an array of "longs" directly to an array of "doubles" and similar with something like:

public long[] toLongs(byte[] buf) {
    int end = buf.length >> 3;
    long[] newArray = new long[end];
    for (int ii = 0; ii < end; ++ii) {
        newArray[ii] = (long)AS_LONGS_VH.get(buf, ALIGN_OFFSET + ii << 3);
    }
}

private static final ALIGN_OFFSET = ByteBuffer.wrap(new byte[0]).alignmentOffset(8); 
private static final VarHandle AS_LONGS_VH = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder());

This will let you do the bit hacking like:

float thefloat = 0.4;
int floatBits;
_Static_assert(sizeof theFloat == sizeof floatBits, "this bit twiddling hack requires floats to be equal in size to ints");
memcpy(&floatBits, &thefloat, sizeof floatBits);

No. Java does not have an equivalent to memcpy. Java has an equivalent to memmove instead.

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

Oracle Docs

It is very likely System.arraycopy will never have the same performance as memcpy if src and dest refer to the same array. Usually this will be fast enough though.

Related