栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ByteBuffer.clear()

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ByteBuffer.clear()

在学习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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/305975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号