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
相关用法
- Java DoubleBuffer allocate()用法及代码示例
- Java ShortBuffer allocate()用法及代码示例
- Java FloatBuffer allocate()用法及代码示例
- Java ByteBuffer allocate()用法及代码示例
- Java StringReader read(CharBuffer)用法及代码示例
- Java Reader read(CharBuffer)用法及代码示例
- Java CharArrayReader read(CharBuffer)用法及代码示例
- Java CharsetEncoder encode(CharBuffer in)用法及代码示例
- Java CharBuffer limit()用法及代码示例
- Java CharBuffer length()用法及代码示例
- Java CharBuffer order()用法及代码示例
- Java CharBuffer mark()用法及代码示例
- Java CharBuffer charAt()用法及代码示例
- Java CharBuffer chars()用法及代码示例
- Java CharBuffer clear()用法及代码示例
注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 CharBuffer allocate() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。