ByteBuffer.clear()

本文详细解读了Java NIO中ByteBuffer的clear()方法,说明其并非真正清除数据,而是重置position和limit。讲解了clear()在数据读写操作中的作用,并提到了与compact()方法的区别。
摘要由CSDN通过智能技术生成

在学习Java NIO中看到关于Buffer的部分时提到bytebuffer调用clear()方法不会真正的删除掉buffer中的数据,只是把position移动到最前面,同时把limit调整为capacity。源码:

public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }

官方概述:This method does not actually erase the data in the buffer, but it * is named as if it did because it will most often be used in situations * in which that might as well be the caseClears this buffer. The position is set to zero, the limit is set to * the capacity, and the mark is discarded. *

关键一句就是 This method does not actually erase the data in the buffer,它并没有清除数据,只是把光标设置第一个位置上,限制变成容量大小。

调用clear()方法:position将被设回0,limit设置成capacity,换句话说,Buffer看起来被清空了,其实Buffer中的数据并未被清除,只是这些标记告诉我们可以从哪里开始往Buffer里写数据。

如果Buffer中有一些未读的数据,调用clear()方法,数据将“被遗忘”,意味着不再有任何标记会告诉你哪些数据被读过,哪些还没有。

如果Buffer中仍有未读的数据,且后续还需要这些数据,但是此时想要先写些数据,那么使用 compact() 方法。compact()方法将所有未读的数据拷贝到Buffer起始处。然后将position设到最后一个未读元素正后面。limit属性依然像clear()方法一样,设置成capacity。现在Buffer准备好写数据了,但是不会覆盖未读的数据。

另有文章:

  1. https://blog.csdn.net/pfnie/article/details/52829549
  2. https://blog.csdn.net/qq_22701869/article/details/107091427
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值