In Java, the array()
method of the ByteBuffer
class returns the array that backs a provided ByteBuffer
object.
The process is illustrated below.
Any changes to the ByteBuffer
object’s content are reflected in the array returned by the array()
method.
To use the array()
method, you will need to import the ByteBuffer
class into your program, as shown below.
import java.nio.ByteBuffer
The prototype of the array()
method is shown below.
public final byte[] array()
The array()
method does not accept any parameters.
The array()
method returns a byte array that backs the given ByteBuffer
object.
If the buffer is backed by an array but is set to read-only
, then the array()
method throws the ReadOnlyBufferException.
Similarly, if the buffer is not backed by an array, the array()
method throws the UnsupportedOperationException.
The code below shows how the array()
method can be used in Java.
import java.nio.*;import java.util.*;class arrayMethod {public static void main(String[] args) {// initialize ByteBuffer instanceByteBuffer buffer = ByteBuffer.allocate(6);byte values[] = {2, 1, 6, 7, 10};// add values to bufferfor(int i = 0; i < 5; i++){buffer.put(values[i]);}// get array that backs bufferbyte [] bufferArray = buffer.array();// Print buffer arraySystem.out.println("The buffer array is: " + Arrays.toString(bufferArray));// update bufferbuffer.put((byte)20);bufferArray = buffer.array();System.out.println("The new buffer array is: " + Arrays.toString(bufferArray));// create a read-only copyByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();// get backing arraytry{byte [] readOnlyArray = readOnlyBuffer.array();}catch (ReadOnlyBufferException error){System.out.println("An exception was thrown: " + error);}}}
First, a ByteBuffer
object called buffer
is initialized through the allocate()
method. buffer
has the capacity to store elements.
Next, a for-loop
adds values to buffer
through the put()
method.
The array()
method in line proceeds to return the backing array for the buffer
object. The contents of the array reflect the contents of buffer
. Therefore, the addition of new values to buffer
changes the backing array. As a result, the array()
method in line returns a different array than the one before.
Finally, a read-only
copy of buffer
is created through the asReadOnlyBuffer()
method. The array()
method in line throws the ReadOnlyBufferException
when it tries to return the backing array.