Java 中的 ByteBuffer asShortBuffer() 方法
java 8object oriented programmingprogramming
可以使用 java.nio.ByteBuffer 类中的 asShortBuffer() 方法将 ByteBuffer 视图创建为 ShortBuffer。此方法不需要参数,并根据需要返回一个短缓冲区。此缓冲区反映了对原始缓冲区所做的更改,反之亦然。
下面给出了一个演示此操作的程序 −
示例
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 50; try { ByteBuffer bufferB = ByteBuffer.allocate(n); ShortBuffer bufferS = bufferB.asShortBuffer(); bufferS.put((short)5); bufferS.put((short)9); bufferS.put((short)2); bufferS.put((short)8); bufferS.put((short)3); bufferS.rewind(); short s; System.out.print("The ShortBuffer is: "); while ((s = bufferS.get()) != 0) { System.out.print(s + " "); } } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e){ System.out.println("Error!!! ReadOnlyBufferException"); } } }
输出
The ShortBuffer is: 5 9 2 8 3