Java中的CharBuffer allocate()方法及其示例

这个 分配 方法 JAVA尼奥。CharBuffer类 用于分配新的 字符缓冲区 在现有缓冲区旁边。新缓冲区的位置将为零。它的极限将是它的容量。它的标志将是不明确的。它的每个元素都将被初始化为零。它将有一个支持数组,其数组偏移量将为零。

null

语法:

public static CharBuffer allocate(int capacity)

参数: 此方法采用新缓冲区的 容量 ,以字符表示,作为参数。

返回值 :此方法返回 新的字符缓冲区 .

例外情况: 这个方法抛出了 非法数据异常 如果容量为负整数。

下面的程序演示了allocate()方法:

例1:

JAVA

// 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: 证明非法辩论的例外

JAVA

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

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享