Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between rewind() and clear() of class ByteBuffer?

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?

like image 367
liujyg Avatar asked Feb 12 '23 07:02

liujyg


2 Answers

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.

like image 28
sofia Avatar answered Feb 15 '23 11:02

sofia


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.

like image 126
webuster Avatar answered Feb 15 '23 09:02

webuster