Java 中的 FloatBuffer slice() 方法
可以使用 java.nio.FloatBuffer 类中的 slice() 方法来创建包含与原始 FloatBuffer 相同的共享子序列的新 FloatBuffer。如果原始缓冲区是只读的,此方法会返回一个新的只读 FloatBuffer;如果原始缓冲区是直接的,它会返回一个新的直接 FloatBuffer。
以下给出的程序对此进行了演示:
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { FloatBuffer buffer1 = FloatBuffer.allocate(n); buffer1.put(4.5F); buffer1.put(1.2F); buffer1.put(3.9F); System.out.println("The Original FloatBuffer is: " + Arrays.toString(buffer1.array())); System.out.println("The position is: " + buffer1.position()); System.out.println("The capacity is: " + buffer1.capacity()); FloatBuffer buffer2 = buffer1.slice(); System.out.println("
The Subsequence FloatBuffer is: " + Arrays.toString(buffer2.array())); System.out.println("The position is: " + buffer2.position()); System.out.println("The capacity is: " + buffer2.capacity()); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
上述程序的输出如下:
输出
The Original FloatBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0] The position is: 3 The capacity is: 5 The Subsequence FloatBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0] The position is: 0 The capacity is: 2
广告