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


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


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

用法:

public static CharBuffer allocate(int capacity)

參數:此方法將以char為單位的新緩衝區的容量作為參數。


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

異常:如果容量為負整數,則此方法引發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 CharBuffer 
        char capacity = 10; 
  
        // Creating the CharBuffer 
  
        // creating object of Charbuffer 
        // and allocating size capacity 
        CharBuffer fb = CharBuffer.allocate(capacity); 
  
        // putting the value in charbuffer 
        fb.put('a'); 
        fb.put(3, 'b'); 
  
        // Printing the CharBuffer 
        System.out.println("ChartBuffer: "
                           + Arrays.toString(fb.array())); 
    } 
}
輸出:
ChartBuffer: [a, , , b, , , , , , ]

範例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 CharBuffer 
        // by negetive integer 
        int capacity = -10; 
  
        // Creating the CharBuffer 
        try { 
  
            // creating object of CharBuffer 
            // and allocating size with negative integer 
            System.out.println("Trying to allocate a negative integer"); 
  
            CharBuffer fb = CharBuffer.allocate(capacity); 
        } 
        catch (IllegalArgumentException e) { 
            System.out.println("Exception thrown: " + e); 
        } 
    } 
}
輸出:
Trying to allocate a negative integer
Exception thrown: java.lang.IllegalArgumentException


相關用法


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