![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e163. Creating a Non-Byte Java Type Buffer on a ByteBufferYou can create views on aByteBuffer 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 // Obtain a ByteBuffer; see also e158 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
e159. Getting Bytes from a ByteBuffer e160. Putting Bytes into a ByteBuffer e161. Converting Between a ByteBuffer an a Byte Array e162. Getting and Setting Non-Byte Java Types in a ByteBuffer e164. Using a ByteBuffer to Store Strings e165. Setting the Byte Ordering for a ByteBuffer
© 2002 Addison-Wesley. |