Java - Different Views of a Buffer

Introduction

A view of a buffer shares data with the original buffer and maintains its own position, mark, and limit.

Use the duplicate() method of a buffer to get a copy of the buffer as follows:

// Create a buffer
ByteBuffer bb = ByteBuffer.allocate(1024);

// Create a duplicate view of the buffer
ByteBuffer bbDuplicate = bb.duplicate();

You can create a view of a buffer that reflects only a portion of the contents of the original buffer.

slice() method of a buffer creates a sliced view.

// Create a buffer
ByteBuffer bb = ByteBuffer.allocate(8);

// Set the position and the limit before getting a slice
bb.position(3);
bb.limit(6);

// myBuffer buffer will share data of bb from index 3 to 5.
// myBuffer will have position set to 0 and its limit set to 3.
ByteBuffer myBuffer = bb.slice();

To create a view of a byte buffer for different primitive data types, use asXXXBuffer() method.

For example, you can get a character view, a float view, etc. of a byte buffer.

ByteBuffer class contains methods such as asCharBuffer(), asLongBuffer(), asFloatBuffer(), etc. to obtain a view for primitive data types.

// Create a byte buffer
ByteBuffer bb = ByteBuffer.allocate(8);

// Create a char view of the byte buffer
CharBuffer cb = bb.asCharBuffer();

// Create a float view of the byte buffer
FloatBuffer fb = bb.asFloatBuffer();

Related Topic