I have a ByteBuffer
containing three double values, e.g. {1.0, 2.0, 3.0}
. What I have now is
double[] a = new double[3];
for (int i = 0; i < 3; i++) {
a[i] = byteBuffer.getDouble();
}
which works fine, but I would prefer a one-step solution via
double[] a = byteBuffer.asDoubleBuffer().array();
but this results in a exception:
java.lang.UnsupportedOperationException at java.nio.DoubleBuffer.array(...)
What am I doing wrong?
According to the documentation, array
is an optional operation:
public final double[] array()
Returns the double array that backs this buffer (optional operation).
You can tell if calling array
is OK by calling hasArray()
.
You can make an array as follows:
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
You're misusing DoubleBuffer
. DoubleBuffer.array()
returns the array that's backing the DoubleBuffer
if and only if it is the kind of DoubleBuffer
that is backed by an array. This one isn't. It's backed by a ByteBuffer
. In fact, this DoubleBuffer
is just a view of the original ByteBuffer
.
You can find out whether any particular ByteBuffer
is backed by an array by invoking the hasArray()
method.
See Peter Lawrey's answer for the code to get the contents of a DoubleBuffer
into an array of double
. (He beat me to it. :-) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With