Java Reference
In-Depth Information
You can also
slice
any of the buffers we have seen. Calling the
slice()
method for a buffer will return
a reference to a new buffer object of the same type as the original that shares the elements remaining in
the original buffer. In other words, it maps to a part of the original buffer starting at the element at its
current position, up to and including the element at
limit-1
. Of course, if the position of the original
buffer object is zero and the limit is equal to the capacity, the
slice()
method effectively produces the
same result as the
duplicate()
method, that is the entire buffer will be shared. Slicing a buffer gives
you access to the data in a given part of a buffer through two or more separate routes, each with its own
independent position and limit.
Creating Buffers by Wrapping Arrays
You can also create a buffer by wrapping an existing array of the same type as the buffer elements by
calling one of the static
wrap()
method in the
Buffer
class. This creates a buffer that already contains
the data in the array. For example, you could create a
ByteBuffer
object by wrapping an array of
type
byte[]
, like this:
String saying = "Handsome is as handsome does.";
byte[] array = saying.getBytes(); // Get string as byte array
ByteBuffer buf = ByteBuffer.wrap(array);
Of course, you could convert the string to a byte array and create the buffer in a single statement:
ByteBuffer buf = ByteBuffer.wrap(saying.getBytes());
In any event, the buffer object will not have memory of its own to store the data. The buffer will be
backed by the byte array that we have used to define it so modifications to the elements in the buffer
will alter the array, and vice versa. The capacity and limit for the buffer will be set to the length of the
array and its position will be zero.
You can also wrap an array to create a buffer so that the position and limit correspond to a particular
sequence of elements in the array. For example:
String saying = "Handsome is as handsome does.";
byte[] array = saying.getBytes(); // Get string as byte array
ByteBuffer buf = ByteBuffer.wrap(array, 9, 14);
This creates a buffer by wrapping the whole array as before, but the position and limit are set using the
second and third argument, in effect specifying the subsection of the array that can be read or written.
ByteBuffer buf = ByteBuffer.wrap(array, 9, 14);
capacity = array.length = 29
array
H a
n ds om e
i
sash a
n ds om edoes.
position = 9
limit = position+14 = 23
buf