When converting a ByteBuffer to an int array java unexpectedly throws an UnsupportedOperationException.
However as a byte array the information is correctly represented.
int[] intArray = new int[]{1, 2};
ByteBuffer byteBuffer = ByteBuffer.allocate(intArray.length * 4);
IntBuffer ib = byteBuffer.asIntBuffer();
ib.put(intArray);
System.out.println(Arrays.toString(byteBuffer.array())); // prints [0, 0, 0, 1, 0, 0, 0, 2]
System.out.println(Arrays.toString(ib.array())); // Fails with exception UnsupportedOperationException
Reading through other posts I saw this exception in case there was no array to back up the ByteBuffer, but in this case the buffer has enough bytes allocated and should be able to return an int[].
Why is this exception thrown?
(Using java11)
int[].” You seem to be under the impression that thearray()method converts the buffer’s contents to an array, like Collection.toArray or Stream.toArray, but that is not the case. As Slaw explained, it returns the array that directly backs the buffer; if the buffer wasn’t created directly from an int array, you get an UnsupportedOpertaionException.ByteBufferto anint[]without allocating new memory for theint[]. The best you could do is make use of theIntBufferyou created via#asIntBuffer(). Obviously, that allocates memory for theIntBufferinstance, but both theByteBufferand theIntBufferwill be backed by the samebyte[]instance.