Java Reference
In-Depth Information
When you create a new independent buffer, its capacity will be fixed at a value that you specify. It will
also have a position of zero and its limit will be set to its capacity. When you create a view buffer from
an existing ByteBuffer , the contents of the view buffer starts at the current position for the
ByteBuffer . The capacity and limit for the view buffer will be set to the limit for the original buffer,
divided by the number of bytes in an element in the view buffer. The limit and position for the view
buffer will subsequently be independent of the limit and position for the original buffer.
Setting the Position and Limit
You can set the position and limit for a buffer explicitly by using the following methods defined in the
Buffer class:
Method
Description
position(int
newPosition)
Sets the position to the index value specified by the
argument. The new position value must be greater than
or equal to zero, and not greater than the current limit,
otherwise an exception of type
IllegalArgumentException will be thrown. If the
buffer's mark is defined (we will come to the mark in
the next section) and greater than the new position, it
will be discarded.
limit(int newLimit)
Sets the limit to the index value specified by the
argument. If the buffer's position is greater than the
new limit it will be set to the new limit. If the buffer's
mark is defined and exceeds the new limit it will be
discarded. If the new limit value is negative or greater
than the buffer's capacity, an exception of type
IllegalArgumentException will be thrown.
Both of these methods return a reference of type Buffer for the object for which they were called. This
enables you to chain them together in a single statement. For instance, given a buffer reference, buf ,
you could set both the position and the limit with the statement:
buf.limit(512).position(256);
This assumes the capacity of the buffer is at least 512 elements. If you are explicitly setting both the
limit and the position you should always choose the sequence in which you set them to avoid setting a
position that is greater than the limit. If the buffer's limit starts out less than the new position you want
to set, attempting to set the position first will result in an IllegalArgumentException being
thrown. Setting the limit first to a value less than the current position will have a similar effect. If you
want to avoid checking the current limit and position when you want to reset both, you can always do it
safely like this:
buf.position(0).limit(newLimit).position(newPosition);
Of course, the new position and limit values must be legal; otherwise an exception will still be thrown.
In other words newPosition must be non-negative, and less than newLimit . To be 100% certain
setting a new position and limit is going to work, you could code it something like this:
Search WWH ::




Custom Search