缓冲区其实就是一块数组,然后对这一块数组进行一系列的操作,它包括以下几个常用的方法:
1分配空间给缓冲区
2.往缓冲区中添加数据调用put方法
3.调用flip方法切换为读状态
4.读取完毕调用clear方法重新设置位置为0。
1.clear方法不清除数据,只是改变当前limit值
- public final Buffer clear() {
- position = 0;
- limit = capacity;
- mark = -1;
- return this;
- }
2.flip方法允许输出
- public final Buffer flip() {
- limit = position;
- position = 0;
- mark = -1;
- return this;
- }
3.rewind方法使posotion方法置为0
- public final Buffer rewind() {
- position = 0;
- mark = -1;
- return this;
- }
4.判断两个缓冲区是否相等的方法,代码如下:
- public boolean equals(Object ob) {
- if (this == ob)
- return true;
- if (!(ob instanceof CharBuffer))
- return false;
- CharBuffer that = (CharBuffer)ob;
- if (this.remaining() != that.remaining())
- return false;
- int p = this.position();
- for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
- if (!equals(this.get(i), that.get(j)))
- return false;
- return true;
- }
要满足几下条件才能算相等。
1、对象要相同
2、剩余的空间要相同
3、从position到limit区间的数据要相等才能确认数据是否相等。
来源: http://www.bubuko.com/infodetail-2413579.html