Java Reference
In-Depth Information
position in the buffer. The following statements extend the previous example and display
everything in the integer buffer:
for (int i = 0; tempBuffer.remaining() > 0; i++)
System.out.println(tempBuffer.get());
Another way to create a buffer is to set up an empty buffer and then put data into it. To
create the buffer, call the static method allocate( int ) of the desired buffer class with
the size of the buffer as an argument.
You can use five put() methods to store data in a buffer (or replace the data already
there). The arguments used with these methods depend on the kind of buffer you're
working with. For an integer buffer:
put( int ) —Stores the integer at the current position in the buffer and then incre-
ments the position.
n
put( int , int ) —Stores an integer (the second argument) at a specific position in
the buffer (the first argument).
n
put( int[] ) —Stores all the elements of the integer array in the buffer, beginning at
the first position of the buffer.
n
put( int[] , int , int ) —Stores all or a portion of an integer array in the buffer.
The second argument specifies the position in the buffer where the first integer in
the array should be stored. The third argument specifies the number of elements
from the array to store in the buffer.
n
put( IntBuffer ) —Stores the contents of an integer buffer in another buffer, begin-
ning at the first position of the buffer.
n
As you put data in a buffer, you must often keep track of the current position so that you
know where the next data will be stored.
To find out the current position, call the buffer's position() method. An integer is
returned that represents the position. If this value is 0 , you're at the start of the buffer.
Call the position( int ) method to change the position to the argument specified as an
integer.
Another important position to track when using buffers is the limit—the last place in the
buffer that contains data.
It isn't necessary to figure out the limit when the buffer is always full; in that case, you
know the last position of the buffer has something in it.
Search WWH ::




Custom Search