The asIntBuffer()
method of the ByteBuffer
class in Java creates a view of a given ByteBuffer
object as an IntBuffer
.
The content of IntBuffer
starts from ByteBuffer
's current buffer position. Any changes made to ByteBuffer
are reflected in IntBuffer
, and vice versa.
The position
, mark
, and limit
values of the two buffers are independent.
The process is illustrated below:
To use the asIntBuffer()
method, you will need to include the ByteBuffer
class in your program, as shown below:
import java.nio.ByteBuffer
The prototype of the asIntBuffer()
method is shown below:
public abstract IntBuffer asIntBuffer()
The asIntBuffer()
method does not accept any parameters.
The asIntBuffer()
method returns a new IntBuffer
object that is a view of a specified ByteBuffer
object.
The properties of the newly created IntBuffer
object are as follows:
capacity
and limit
are defined as the number of bytes that remain in the ByteBuffer
object divided by .mark
value is undefined.IntBuffer
will be direct
if, and only if, the ByteBuffer
object is direct
. Similarly, IntBuffer
will be read-only
if, and only if, the ByteBuffer
object is read-only
.The code below shows how the asIntBuffer()
method can be used in Java:
import java.nio.*;import java.util.*;class asIntBufferMethod {public static void main(String[] args) {// initialize ByteBuffer instanceByteBuffer sourceBuffer = ByteBuffer.allocate(16);// get int buffer viewIntBuffer newBuffer = sourceBuffer.asIntBuffer();int values[] = {2, 1, 6};// add values to bufferfor(int i = 0; i < 3; i++){newBuffer.put(values[i]);}// set buffer position to first indexnewBuffer.rewind();// print source bufferSystem.out.println("The ByteBuffer is: " + Arrays.toString(sourceBuffer.array()));//print new bufferint i;System.out.print("The IntBuffer is: [");while ((i = newBuffer.get()) != 0){System.out.print(i + " ");}System.out.print("]");}}
First, a ByteBuffer
object, sourceBuffer
, is initialized through the allocate()
method. sourceBuffer
has the capacity to store elements.
Next, an IntBuffer
view of sourceBuffer
is created through the asIntBuffer()
method in line .
The put()
method is repeatedly invoked through a for-loop
to add values to newBuffer
.
All the changes made to newBuffer
are also reflected in sourceBuffer
. However, since sourceBuffer
holds byte elements, each integer value added to newBuffer
is the equivalent of byte values added to sourceBuffer
.
For example, the addition of the element to
newBuffer
is reflected by the addition of elements, i.e., , tosourceBuffer
.