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 negative 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