📌  相关文章
📜  Java中的 ShortBuffer allocate() 方法及示例

📅  最后修改于: 2022-05-13 01:54:51.668000             🧑  作者: Mango

Java中的 ShortBuffer allocate() 方法及示例

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

public static ShortBuffer allocate(int capacity)

参数:该方法接受一个强制参数容量,它指定新缓冲区的容量,简而言之。
返回值:此方法返回新的ShortBuffer
异常:如果容量为负整数,此方法将引发IllegalArgumentException
下面的程序说明了allocate()方法的使用:
方案一:

Java
// 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()));
    }
}


Java
// 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);
        }
    }
}


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

程序 2:显示 NullPointerException

Java

// 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 integer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)

参考: https: Java/nio/ShortBuffer.html#allocate()