Search code examples
javaniobytebuffernio2

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?


Solution

  • 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