Reputation: 809
What is the best way to do that?
I tried the following:
ByteBuffer cacheBuffer=ByteBuffer.allocateDirect(nm(nLimit,0)); //where nm(nLimit,0) is a large number
double[] cache=cacheBuffer.asDoubleBuffer().array();
But I got this exception:
java.lang.UnsupportedOperationException
at java.nio.DoubleBuffer.array(Unknown Source)
Why?
Edit:
It looks like the javadoc "Returns the double array that backs this buffer (optional operation)." actually means array() method is simply returning the double array that is already backing this buffer. I thought it is going to convert the buffer to double[] somehow. So now it makes sense I got an exception.
Upvotes: 2
Views: 2691
Reputation: 7234
array() is an optional operation of Buffers. Buffer implementations may/ may not support this operation. Invoke hasArray() to check if the operation is supported and then proceed accordingly.
Upvotes: 1
Reputation: 29636
This will only work if you expect your array to merely be a copy.
final DoubleBuffer buffer = cacheBuffer.asDoubleBuffer();
final double[] copy = new double[buffer.remaining()];
buffer.get(copy);
The reason your attempt fails is because array
is only supported for non-direct buffers; direct buffers are not backed by an array.
Upvotes: 6