Java Reference
In-Depth Information
A buffer produced by the slice() method 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 buffer memory is 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() methods. This method creates a buffer that already contains the data in the array.
You saw earlier that you can create a ByteBuffer object by wrapping an array of type byte[] .
When you create a buffer by wrapping an array, the buffer object does not have memory of its own to
store the data. The buffer is backed by the array that you have used to define it, so modifications to the val-
ues in the buffer alters the array, and vice versa. The capacity and limit for the buffer are set to the length of
the array, and its position is zero.
You can also wrap an array to create a buffer so that the position and limit correspond to a particular se-
quence 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 a byte array, but the position and limit are set using the second and
third argument. The second and third arguments to the wrap() method specify the subsection of the array
that is to be read or written next. This is illustrated in Figure 10-6 .
FIGURE 10-6
 
 
Search WWH ::




Custom Search