ByteBuffer.clear()学习记录

本文围绕Java NIO中Buffer展开,介绍了clear()方法。该方法不会真正删除Buffer中的数据,只是将position移到最前,limit设为capacity。若Buffer有未读数据且后续还需,可使用compact()方法,它会拷贝未读数据到起始处,再设置好position和limit,以便写入新数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学习JavaNIO中看到关于Buffer的部分时提到buffer调用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准备好写数据了,但是不会覆盖未读的数据。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值