当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ShortBuffer allocate()用法及代码示例


java.nio.ShortBuffer类的allocate()方法用于分配新的短缓冲区。

尽管标记未定义,但新缓冲区的位置将为零且其容量是其极限,并且每个元素都初始化为零。它将有一个支持数组,且数组偏移为零。

用法


public static ShortBuffer allocate(int capacity)

参数:该方法接受强制性参数容量,以简写形式指定新缓冲区的容量。

返回值:此方法返回新的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 negetive 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 negetive integer"); 
  
            FloatBuffer fb = FloatBuffer.allocate(capacity); 
        } 
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
输出:
Trying to allocate a negetive integer
Exception thrown: java.lang.IllegalArgumentException

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



相关用法


注:本文由纯净天空筛选整理自IshwarGupta大神的英文原创作品 ShortBuffer allocate() method in Java With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。