我有一个 ByteBuffer
包含三个 double 值,例如{1.0、2.0、3.0}
。我现在拥有的是
double[] a = new double[3];
for (int i = 0; i < 3; i++) {
a[i] = byteBuffer.getDouble();
}
效果很好,但我更喜欢通过
的一步解决方案double[] a = byteBuffer.asDoubleBuffer().array();
但这会导致异常:
java.lang.UnsupportedOperationException at java.nio.DoubleBuffer.array(...)
我做错了什么?
最佳答案
根据documentation , array
是可选操作:
public final double[] array()
Returns the double array that backs this buffer (optional operation).
您可以通过调用 hasArray()
来判断调用 array
是否正常。
你可以像下面这样创建一个数组:
DoubleBuffer dbuf = byteBuffer.asDoubleBuffer(); // Make DoubleBuffer
double[] a = new double[dbuf.remaining()]; // Make an array of the correct size
dbuf.get(a); // Copy the content into the array
关于java - 从 ByteBuffer 到双数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513068/