4

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?

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Michael Dorner
  • 17,587
  • 13
  • 87
  • 117

4 Answers4

7

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
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
6

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

Erick G. Hagstrom
  • 4,873
  • 1
  • 24
  • 38
4

The DoubleBuffer has two modes: it can either work by allocation or as a view. This is decided exclusively at the time of the creation of the DoubleBuffer.

The array() method is optional and will throw a UnsupportedOperationException if you're using it from the view.

In your case, coming from a ByteBuffer to a DoubleBuffer using the method ByteBuffer::asDoubleBuffer, you get a view, as mentioned in the Javadoc. And since it's a view, you get the exception.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
2

You can copy to a double[] with this.

double[] doubles = new double[byteBuffer.remaining() / Double.BYTES];
byteBuffer.asDoubleBuffer().get(doubles);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130