Java Reference
In-Depth Information
The buffer's capacity is
array.length
and the position is set to the value of the second argument, 9. The
third argument specifies the number of buffer elements that can be read or written so this value is added to
the position to define the limit. If either the second argument value or the sums of the second and third argu-
ment values do not represent legal index values for the array, then an exception of type
IndexOutOfBound-
sException
is thrown.
You can also wrap arrays of values of a primitive type to create a buffer of the corresponding type. For
example:
long[] numbers = { 1L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L};
LongBuffer numBuf = LongBuffer.wrap(numbers);
The buffer of type
LongBuffer
that you create here has a capacity of
array.length
, which is 11. The
buffer position is set to 0 and the limit is set to the capacity. In a similar manner you can create buffers from
arrays of any of the other primitive types with the exception of type
boolean
. Creating buffers other that
ByteBuffer
objects in this way is of little value with channel operations because you cannot use then direc-
tly in I/O operations.
Marking a Buffer
You use the
mark
property for a buffer to record a particular index position in the buffer that you want to be
able to return to later. You can set the mark to the current position by calling the
mark()
method for a buffer
object that is inherited from the
Buffer
class. For example:
buf.mark(); // Mark the current position
This method also returns a reference of type
Buffer
so you could chain it with the methods for setting
the limit and position:
buf.limit(512).position(256).mark();
This sets the mark to 256, the same as the position, which is set after the limit has been set to 512.
After a series of operations that alter the position, you can reset the buffer's position to the mark that you
have set previously by calling the
reset()
method that is inherited from the
Buffer
class:
buf.reset(); // Reset position to last marked