Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From ByteBuffer to double array

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?

like image 324
Michael Dorner Avatar asked Dec 01 '22 13:12

Michael Dorner


2 Answers

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
like image 133
Sergey Kalinichenko Avatar answered Dec 11 '22 06:12

Sergey Kalinichenko


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. :-) )

like image 33
Erick G. Hagstrom Avatar answered Dec 11 '22 04:12

Erick G. Hagstrom