Java ShortBuffer allocate()方法及示例

来源:这里教程网 时间:2026-02-17 21:09:08 作者:

Java ShortBuffer allocate()方法及示例

java.nio.ShortBuffer 类的 allocate() 方法用于分配一个新的短缓冲区。
新缓冲区的位置将是零,它的极限是它的容量,尽管标记是未定义的,而且它的每个元素都被初始化为零。它将有一个支持数组,数组的偏移量为零。
语法

public static ShortBuffer allocate(int capacity)

参数 :该方法接受一个强制性参数 capacity ,该参数指定了新缓冲区的容量,单位为shorts。
返回值 :该方法返回新的 ShortBuffer。
异常 :该方法抛出 IllegalArgumentException ,如果容量是一个负整数。
以下程序说明了 allocate( 方法的使用:
程序1:

// Java program to demonstrate// allocate() method import java.nio.*;import java.util.*; public class GFG {    public static void main(String[] args)    {         // Declaring the capacity of the ShortBuffer        int capacity = 5;         // Creating the ShortBuffer         // creating object of Shortbuffer        // and allocating size capacity        ShortBuffer sb = ShortBuffer.allocate(capacity);         // putting the value in Shortbuffer        sb.put((short)10000);        sb.put((short)10640);        sb.put((short)10189);        sb.put((short)-2000);        sb.put((short)-16780);         // Printing the ShortBuffer        System.out.println("ShortBuffer: "                           + Arrays.toString(sb.array()));    }}

输出

ShortBuffer: [10000, 10640, 10189, -2000, -16780]

程序2: 要显示NullPointerException

// Java program to demonstrate// allocate() method import java.nio.*;import java.util.*; public class GFG {    public static void main(String[] args)    {         // Declaring the capacity of the ShortBuffer        // by negative integer        int capacity = -10;         // Creating the ShortBuffer        try {             // creating object of shortbuffer            // and allocating size with negative integer            System.out.println("Trying to allocate a negative integer");             FloatBuffer fb = FloatBuffer.allocate(capacity);        }        catch (IllegalArgumentException e) {            System.out.println("Exception thrown: " + e);        }    }}

输出

Trying to allocate a negative integerException thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)

**参考资料: ** https://docs.oracle.com/javase/7/docs/api/java/nio/ShortBuffer.html#allocate()

相关推荐