可以使用asIntBuffer()
类java.nio.ByteBuffer中的方法将ByteBuffer的视图创建为IntBuffer 。此方法不需要任何参数,并且根据需要返回int缓冲区。该缓冲区反映了对原始缓冲区所做的更改,反之亦然。
演示此的程序如下所示-
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 50; try { ByteBuffer bufferB = ByteBuffer.allocate(n); IntBuffer bufferI = bufferB.asIntBuffer(); bufferI.put(3); bufferI.put(9); bufferI.put(1); bufferI.put(7); bufferI.put(4); bufferI.rewind(); int i; System.out.print("The IntBuffer is: "); while ((i = bufferI.get()) != 0) { System.out.print(i + " "); } } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
输出结果
The IntBuffer is: 3 9 1 7 4