What is the ByteBuffer duplicate() method in Java?
The duplicate() method of the ByteBuffer class in Java creates a new ByteBuffer object that shares the content of another buffer.
The process is illustrated below:
Properties of ByteBuffer
The values in the source ByteBuffer are all copied into the newly created buffer. Any changes made to the original buffer are reflected in the new buffer and vice versa.
The properties of the new buffer, e.g., position, limit, and capacity, are identical to the source buffer; however, these properties are also independent.
Similarly, properties such as whether the new buffer is direct or read-only depend on the properties of the source buffer.
You can check the documentation for a comprehensive guide on the properties of a
ByteBuffer.
Syntax
To use the duplicate() method, you will need to import the ByteBuffer class into your program, as shown below:
import java.nio.ByteBuffer
Parameters
The duplicate() method does not accept any parameters.
Return value
The duplicate() method returns the newly created ByteBuffer object.
Code
The code below shows how the duplicate() method can be used in Java:
import java.nio.*;import java.util.*;class duplicateMethod {public static void main(String[] args) {// initialize buffer instanceByteBuffer sourceBuffer = ByteBuffer.allocate(5);// add values to buffersourceBuffer.put((byte)2);sourceBuffer.put((byte)4);sourceBuffer.put((byte)10);// create a duplicate bufferByteBuffer newBuffer = sourceBuffer.duplicate();// Print buffersSystem.out.println("The source buffer is: " + Arrays.toString(sourceBuffer.array()));System.out.println("The duplicate buffer is: " + Arrays.toString(newBuffer.array()));// add values to source buffersourceBuffer.put((byte)5);sourceBuffer.put((byte)20);// Print buffersSystem.out.println("\nThe updated source buffer is: " + Arrays.toString(sourceBuffer.array()));System.out.println("The updated duplicate buffer is: " + Arrays.toString(newBuffer.array()));}}
Explanation
First, a ByteBuffer object called sourceBuffer is initialized through the allocate() method. sourceBuffer can store five values.
Next, the put() method is invoked three times to add sourceBuffer values.
The duplicate() method is invoked in line to create a new ByteBuffer object called newBuffer. All of the content of sourceBuffer is shared with newBuffer.
Finally, the put() method is invoked to add two more values to sourceBuffer. Since content is shared between both ByteBuffer objects, the changes are also reflected in newBuffer, and both objects are identical when printed.