views:

207

answers:

5

java.nio.ByteBuffer#duplicate() returns a new byte buffer that shares the old buffer's content. Changes to the old buffer's content will be visible in the new buffer, and vice versa. What if I want a deep copy of the byte buffer?

+1  A: 

You'll need to iterate the entire buffer and copy by value into the new buffer.

Kylar
There's an (optional) overload of the `put` method that does this for you though.
nos
Woohoo! I learned something new.
Kylar
A: 

You will have to use System.arraycopy to duplicate the values of the buffer to the new buffer

webdestroya
+1  A: 
public static ByteBuffer copy(ByteBuffer b) {
    byte[] oldBytes = b.array();
    byte[] copiedBytes = new byte[oldBytes.length];
    // (Object src, int srcPos, Object dest, int destPos, int length) 
    System.arraycopy(oldBytes, 0, copiedBytes, 0, oldBytes.length);
    ByteBuffer duplicate = ByteBuffer.wrap(copiedBytes);
    return duplicate;
}

should work, but haven't tested it.

I82Much
A: 

Writing your own code is an option and the answers so far should work fine. For a more generic solution there's also Serialization ( http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2 ) and there are utilities to make deep copies of things, like http://www.genericdeepcopy.com/ and http://robust-it.co.uk/clone/.

Aaron