Java 中的 DoubleBuffer compact() 方法及示例

2025 年 1 月 7 日 | 阅读 3 分钟

Java.nio.DoubleBuffer 类提供了一个 compact() 方法。可以使用 DoubleBuffer 类来压缩给定的缓冲区。值从缓冲区当前位置开始复制到缓冲区的开头,直到缓冲区的界限。然后,将 n+1 赋给缓冲区的下一个插槽,并将其容量设置为其界限。复制的浮点数数量决定了缓冲区的当前位置。

语法

返回值:此方法返回的新 DoubleBuffer 包含与此缓冲区相同的原始内容。

异常:如果缓冲区是只读的,此函数会引发 ReadOnlyBufferException。

示例 1

DoubleBuffer 是 java.nio 包中的一个类,可以用来处理双精度浮点整数缓冲区,如给出的 Java 代码所示。通过使用 compact() 方法创建压缩后的缓冲区,将剩余元素移动到开头,然后该缓冲区即可进行进一步的写入操作。在显示压缩后的缓冲区当前状态并添加新值后,DoubleBuffer 说明了如何有效地处理数据以进行后续操作,同时保留缓冲区的状态,如位置和界限。

实施

文件名:BufferCompactExample1.java

输出

 
The Original DoubleBuffer is given by : [6.320000171661377, 7.650000095367432, 8.720000267028809, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
at the position: 3
at the limit: 10
The Compacted DoubleBuffer is given by : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
at the Position: 7
at the limit: 10
The Updated Compacted DoubleBuffer is given by : [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.609999656677246, 0.0, 0.0]
at the Position: 8
at the limit: 10   

示例 2

该代码演示了如何在 Java 中使用 DoubleBuffer。它首先创建一个容量为 10 个字节的 DoubleBuffer,向其中插入三个浮点整数,然后将其重置。AsReadOnlyBuffer() 创建了缓冲区的只读副本。然后打印出只读缓冲区的当前位置和界限,以及其内容和状态。当尝试使用 compact() 对只读缓冲区进行压缩时,会引发 ReadOnlyBufferException,因为不允许对只读缓冲区执行此操作。

实施

文件名:BufferCompactExample2.java

输出

 
The ReadOnlyBuffer DoubleBuffer is given by: 6.320000171661377, 7.650000095367432, 8.720000267028809, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, at the Position: 0
at the limit: 10
Trying to compact the doublebuff1 ReadOnlyBuffer
The Exception throws java.nio.ReadOnlyBufferException