java charbuffer_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值