可以使用array()类java.nio.FloatBuffer中的方法获取缓冲区的float数组。如果返回的数组被修改,则缓冲区的内容也将被修改,反之亦然。如果缓冲区是只读的,则抛出ReadOnlyBufferException。
演示此的程序如下所示-
示例import java.nio.*;
import java.util.*;
public class Demo {
public static void main(String[] args) {
int n = 5;
try {
FloatBuffer buffer = FloatBuffer.allocate(n);
buffer.put(4.5F);
buffer.put(1.2F);
buffer.put(3.9F);
buffer.put(7.5F);
buffer.put(5.8F);
buffer.rewind();
float[] arr = buffer.array();
System.out.println("The FloatBuffer is: " + Arrays.toString(arr));
} catch (IllegalArgumentException e) {
System.out.println("Error!!! IllegalArgumentException");
} catch (ReadOnlyBufferException e) {
System.out.println("Error!!! ReadOnlyBufferException");
}
}
}
上面程序的输出如下-
输出结果The FloatBuffer is: [4.5, 1.2, 3.9, 7.5, 5.8]