Java Reference
In-Depth Information
The buffer's capacity will be
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 will be added to the position to define the limit. If either the second argument value or the
sums of the second and third argument values do not represent legal index values for the array, then an
exception of type
IndexOutOfBoundsException
will be thrown.
You can also wrap arrays of other basic types to create a buffer of the corresponding type. For example:
long[] numbers = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
LongBuffer numBuf = LongBuffer.wrap(numbers);
The buffer of type
LongBuffer
that we create will have a capacity of
array.length
, which will be
11. The buffer position will be set to 0 and the limit will be set to the capacity. In a similar manner we
can create buffers from arrays of any of the other basic types with the exception of type
boolean
.
If a buffer object has been created from an array, you can obtain a reference to the backing array that is
storing the data in the buffer by calling
array()
for the buffer. For example, for the buffer created by
the previous code fragment, we could obtain a reference to the original array like this:
long[] data = numBuf.array();
The variable data will now contain a reference to the original array,
numbers
, which we used to create
numBuf
. If the buffer had not been created from an array, the
array()
method will throw an
exception of type
UnsupportedOperationException
.
If a buffer object is passed to a method as an argument, you might need to determine whether or not it
has a backing array - before you can call its
array()
method for example, if you plan to alter the
buffer's contents by changing the elements in the array. The
hasArray()
method for a buffer object
will return
true
if the buffer was created from an array, and
false
otherwise. Typical usage of this
method is something like this:
if(numBuf.hasArray()) {
long[] data = numBuf.array();
// Modify the data array directly to alter the buffer...
} else {
// Modify the buffer using put() methods for the buffer object...
}
Obviously you would only take the trouble to do this if modifying the backing array was a whole lot
more convenient or faster than using
put()
methods for the buffer. We will see how we use
put()
methods to modify a buffer's contents very soon.
You can create buffers of type
CharBuffer
by wrapping an object of type
String
, as well as an array
of type
char[]
. For example:
String wisdom = "Many a mickle makes a muckle.";
CharBuffer charBuf = CharBuffer.wrap(wisdom);