Java中的FloatBuffer asReadOnlyBuffer()方法
可以使用asReadOnlyBuffer()
类java.nio.FloatBuffer中的方法使用缓冲区的内容来创建只读float缓冲区。新缓冲区不能做任何修改,因为它是只读缓冲区。但是,新缓冲区的容量,位置,限制等与先前的缓冲区相同。
演示此的程序如下所示-
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { FloatBuffer buffer = FloatBuffer.allocate(5); buffer.put(4.5F); buffer.put(1.2F); buffer.put(3.9F); buffer.put(7.5F); buffer.put(5.8F); buffer.rewind(); System.out.println("The Original FloatBuffer is: " + Arrays.toString(buffer.array())); FloatBuffer roBuffer = buffer.asReadOnlyBuffer(); System.out.println("The ReadOnlyBuffer FloatBuffer is: "); while (roBuffer.hasRemaining()) System.out.print(roBuffer.get() + " "); } 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, 7.5, 5.8] The ReadOnlyBuffer FloatBuffer is: 4.5 1.2 3.9 7.5 5.8