Note that in JDK document's words rewind()
and clear()
looks alike for "cleaning" the ByteBuffer
. Actually the old data exists, furthermore rewind()
should be used before channel-write or get operation and clear()
corresponds to channel-read or put operation.
I feel confused about the given description. What is the difference between these counterparts on earth?
1) Here is clear() method:
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}
The clear( ) method resets a buffer to an empty state. It doesn't change any of the data elements of the buffer but simply sets the limit to the capacity and the position back to 0
2) Here is rewind() method:
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
You can use rewind( ) to go back and reread the data in a buffer that has already been flipped. As you can see: it doesn't change the limit. Sometimes, after read data from a buffer, you may want to read it again, rewind() is the right choice for you.
A difference is that clear
resets the limit to the capacity, therefore preparing your buffer for other data to be written (and read by you), whereas rewind
doesn't do anything to the limit, therefore your data may be read again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With