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


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


java.nio.LongBuffer类的allocate()方法用于在现有缓冲区旁边分配一个新的Long缓冲区。新缓冲区的位置将为零。它的极限将是它的容量。其标记将是不确定的。并且其每个元素都将初始化为零。它将有一个支持数组,其数组偏移量将为零。

用法:

public static LongBuffer allocate(Long capacity)

参数:此方法将新缓冲区的容量Long用作参数。


返回值:此方法返回新的Long缓冲区。

异常:如果容量为负Longeger,则此方法将抛出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 LongBuffer 
        int Capacity = 10; 
  
        // Creating the LongBuffer 
  
        // creating object of Longbuffer 
        // and allocating size capacity 
        LongBuffer ib = LongBuffer.allocate(Capacity); 
  
        // putting the value in Longbuffer 
        ib.put(11); 
        ib.put(2, 19); 
  
        System.out.println("LongBuffer: "
                           + Arrays.toString(ib.array())); 
    } 
}
输出:
LongBuffer: [11, 0, 19, 0, 0, 0, 0, 0, 0, 0]

示例2:演示IllegalArgumentException

// 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 LongBuffer 
        // by negative Longeger 
        int Capacity = -10; 
  
        // Creating the LongBuffer 
        try { 
  
            // creating object of Longbuffer 
            // and allocating size with negative Longger 
            System.out.println("Trying to allocate a Negative Longeger"); 
  
            LongBuffer ib = LongBuffer.allocate(Capacity); 
        } 
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
输出:
Trying to allocate a Negative Longeger
Exception thrown: java.lang.IllegalArgumentException


相关用法


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