Java Reference
In-Depth Information
view of a different segment of the byte buffer in terms of a particular type of value. Figure 10-4 illustrates
this situation.
FIGURE 10-4
The diagram illustrates a byte buffer with a view buffer of type IntBuffer mapped to the first 8 bytes,
and a view buffer of type CharBuffer mapped to the last 12 bytes. All you need to do to achieve this is to
ensure that the position of the byte buffer is set appropriately before you create each view buffer.
Duplicating and Slicing Buffers
You can duplicate any of the buffers that I have discussed by calling the duplicate() method for the buffer.
The method returns a reference to a buffer with the same type as the original, and which shares the contents
and memory of the original buffer. The duplicate buffer initially has the same capacity, position, and limit
as the original. However, although changes to the contents of the duplicate are reflected in the original, and
vice versa, the position and limit for the original buffer and the duplicate are independent of one other. One
use for a duplicate buffer is when you want to access different parts of a buffer's contents concurrently. You
can retrieve data from a duplicate buffer without affecting the original buffer in any way.
Thus a duplicate buffer is not really a new buffer in memory. It is just a new object that provides an
alternative route to accessing the same block of memory that is being used to buffer the data. The duplic-
ate() method returns a reference of a new object of the same type as the original, but has no independent
data storage. It merely shares the memory that belongs to the original buffer object but with independent
position and limit values.
You can also slice any of the buffers you have seen. Calling the slice() method for a buffer returns a
reference to a new buffer object of the same type as the original that shares the elements that remain in the
original buffer. Slicing a buffer is illustrated in Figure 10-5 .
FIGURE 10-5
 
 
 
 
Search WWH ::




Custom Search