From ByteBuffer to Double Array

I have ByteBufferone containing three double values, for example. {1.0, 2.0, 3.0}. Now I have

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 over

double[] a = byteBuffer.asDoubleBuffer().array();

but this leads to an exception:

java.lang.UnsupportedOperationException at java.nio.DoubleBuffer.array(...)

What am I doing wrong?

+4
source share
4 answers

In accordance with the documentation array - an optional operation:

public final double[] array()

Returns a double array that supports this buffer (optional operation).

You can find out if the call called arrayby 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
+4
source

DoubleBuffer. DoubleBuffer.array() , DoubleBuffer , DoubleBuffer, . . ByteBuffer. , DoubleBuffer ByteBuffer.

, - ByteBuffer hasArray().

. Peter Lawrey , DoubleBuffer double. ( .:-))

+5

DoubleBuffer : . DoubleBuffer.

array() UnsupportedOperationException, .

In your case, starting from ByteBufferto DoubleBufferusing the method ByteBuffer::asDoubleBuffer, you get the view as stated in Javadoc. And since this is a view, you get an exception.

+4
source

You can copy on double[]with this.

double[] doubles = new double[byteBuffer.remaining() / Double.BYTES];
byteBuffer.asDoubleBuffer().get(doubles);
+2
source

Source: https://habr.com/ru/post/1622098/


All Articles