當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java IntBuffer allocate()用法及代碼示例


java.nio.IntBuffer類的allocate()方法用於在現有緩衝區旁邊分配一個新的int緩衝區。新緩衝區的位置將為零。它的極限將是它的容量。其標記將是不確定的。並且其每個元素都將初始化為零。它將有一個支持數組,其數組偏移量將為零。

用法:

public static IntBuffer allocate(int capacity)

參數:此方法將新緩衝區的容量int作為參數。


返回值:此方法返回新的int緩衝區。

異常:如果容量為負整數,則此方法引發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 IntBuffer 
        int Capacity = 10; 
  
        // Creating the IntBuffer 
  
        // creating object of intbuffer 
        // and allocating size capacity 
        IntBuffer ib = IntBuffer.allocate(Capacity); 
  
        // putting the value in intbuffer 
        ib.put(11); 
        ib.put(2, 19); 
  
        System.out.println("IntBuffer: "
                           + Arrays.toString(ib.array())); 
    } 
}
輸出:
IntBuffer: [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 IntBuffer 
        // by negative integer 
        int Capacity = -10; 
  
        // Creating the IntBuffer 
        try { 
  
            // creating object of intbuffer 
            // and allocating size with negative integer 
            System.out.println("Trying to allocate a Negative Integer"); 
  
            IntBuffer ib = IntBuffer.allocate(Capacity); 
        } 
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
輸出:
Trying to allocate a Negative Integer
Exception thrown: java.lang.IllegalArgumentException


相關用法


注:本文由純淨天空篩選整理自nitin_sharma大神的英文原創作品 IntBuffer allocate() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。