Java Reference
In-Depth Information
// We use absolute method of reading the data, so that we do
// not affect the position of the buffer
System.out.print("Data: ");
while (bb.hasRemaining()) {
System.out.print(bb.get() + " ");
}
System.out.println();
}
}
After creation:
Position = 0, Limit = 8
Data: 0 0 0 0 0 0 0 0
After populating data:
Position = 0, Limit = 8
Data: 50 51 52 53 54 55 56 57
Apart from the flip() method, there are three more methods of a buffer that change its mark, position, and/or
limit. They are clear() , reset() , and rewind() .
The clear() method of a buffer sets the position to zero, limit to its capacity, and discards its mark. That is, it
sets the buffer's properties as if the buffer has just been created. Note that it does not change any data in the buffer.
Figure 9-9 and 9-10 show the mark, position, and limit of a buffer before and after calling the clear() method.
Typically, you call the clear() method on a buffer before you start filling it with fresh data.
50
51
52
53
54
0
0
0
Buffer Elements >>
Element's Index >>
012345678
P
M
L
Figure 9-9. Buffer's state before calling its clear() method
Buffer Elements >>
50
51
52
53
54
0
0
0
Element's Index >>
012345678
P
L
Figure 9-10. Buffer's state after calling its clear() method. The clear() method discarded the mark
The reset() method sets the position of a buffer equal to its mark. If mark is not defined, it throws an
InvalidMarkException . It does not affect the limit and data of the buffer. Typically, it is called to revisit (for rereading
or rewriting) the buffer's elements starting from the previously marked position and up to the current position. The
mark of the buffer remains unchanged by the reset() method. Figure 9-11 and 9-12 show the states of a buffer before
and after its reset() method is called.
 
Search WWH ::




Custom Search