Creating a Non-Byte Java Type Buffer on a ByteBuffer

You can create views on a ByteBuffer to support buffers of other Java primitive types. For example, by creating a character view on a ByteBuffer, you treat the ByteBuffer like a buffer of characters. The character buffer supports strings directly. Also, hasRemaining() properly works with characters rather than with bytes.

When you create a typed view, it is important to be aware that it is created on top of the bytes between position and limit. That is, the capacity of the new view is (limit – position). The limit of the new view may be reduced so that the capacity is an integral value based on the size of the type. Finally, the view shares the same storage as the underlying ByteBuffer, so any changes to the byte buffer will be seen by the view and visa versa. However, changes to a view's position or limit do not affect the ByteBuffer's properties and visa versa.

// Obtain a ByteBuffer; see also Creating a ByteBuffer
ByteBuffer buf = ByteBuffer.allocate(15);
// remaining = 15

// Create a character ByteBuffer
CharBuffer cbuf = buf.asCharBuffer();
// remaining = 7

// Create a short ByteBuffer
ShortBuffer sbuf = buf.asShortBuffer();
// remaining = 7

// Create an integer ByteBuffer
IntBuffer ibuf = buf.asIntBuffer();
// remaining = 3

// Create a long ByteBuffer
LongBuffer lbuf = buf.asLongBuffer();
// remaining = 1

// Create a float ByteBuffer
FloatBuffer fbuf = buf.asFloatBuffer();
// remaining = 3

// Create a double ByteBuffer
DoubleBuffer dbuf = buf.asDoubleBuffer();
// remaining = 1

Comments

26 Aug 2011 - 12:56am by Monkey (not verified)

Knokced my socks off with knowledge!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.