Java Reference
In-Depth Information
// Get a read-only buffer
ByteBuffer bbReadOnly = bb.asReadOnlyBuffer();
readOnly = bbReadOnly.isReadOnly(); // Assigns true to readOnly
The read-only buffer returned by the asReadOnlyBuffer() method is a different view of the same buffer. That is,
the new read-only buffer shares data with its original buffer. Any modifications to the contents of the original buffer
are reflected in the read-only buffer. A read-only buffer has the same value of position, mark, limit, and capacity as its
original buffer at the time of creation and it maintains them independently afterwards.
Different Views of a Buffer
You can obtain different views of a buffer. A view of a buffer shares data with the original buffer and maintains its own
position, mark, and limit. I discussed getting a read-only view of a buffer in the previous section that does not let its
contents be modified. You can also duplicate a buffer, in which case they share contents, but maintain mark, position,
and limit independently. 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 also create a sliced view of a buffer. That is, you can create a view of a buffer that reflects only a portion of
the contents of the original buffer. You use the slice() method of a buffer to create its sliced view as follows:
// Create a buffer
ByteBuffer bb = ByteBuffer.allocate(8);
// Set the position and the limit before getting a slice
bb.position(3);
bb.limit(6);
// bbSlice buffer will share data of bb from index 3 to 5.
// bbSlice will have position set to 0 and its limit set to 3.
ByteBuffer bbSlice = bb.slice();
You can also get a view of a byte buffer for different primitive data types. For example, you can get a character
view, a float view, etc. of a byte buffer. The 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();
 
Search WWH ::




Custom Search