What is the ByteBuffer asIntBuffer() method in Java?
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()
Parameters
The asIntBuffer() method does not accept any parameters.
Return value
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:
- The current buffer position is set to .
capacityandlimitare defined as the number of bytes that remain in theByteBufferobject divided by .- The
markvalue is undefined. IntBufferwill bedirectif, and only if, theByteBufferobject isdirect. Similarly,IntBufferwill beread-onlyif, and only if, theByteBufferobject isread-only.
Example
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("]");}}
Explanation
-
First, a
ByteBufferobject,sourceBuffer, is initialized through theallocate()method.sourceBufferhas the capacity to store elements. -
Next, an
IntBufferview ofsourceBufferis created through theasIntBuffer()method in line . -
The
put()method is repeatedly invoked through afor-loopto add values tonewBuffer. -
All the changes made to
newBufferare also reflected insourceBuffer. However, sincesourceBufferholds byte elements, each integer value added tonewBufferis the equivalent of byte values added tosourceBuffer.
For example, the addition of the element to
newBufferis reflected by the addition of elements, i.e., , tosourceBuffer.