java bytebuffer arry_Java ByteBuffer hasArray()用法及代码示例

java.nio.ByteBuffer类的hasArray()方法用于确保给定缓冲区是否由可访问的字节数组支持。如果此缓冲区有可访问的后备数组,则返回true,否则返回false。如果此方法返回true,则可以安全地调用array()和arrayOffset()方法,因为它们在支持数组上起作用。

用法:

public final boolean hasArray()

返回值:当且仅当此缓冲区由数组支持并且不是只读时,此方法才会返回true。否则返回false。

下面是说明hasArray()方法的示例:

范例1:当缓冲区由数组支持时

// Java program to demonstrate

// hasArray() method

import java.nio.*;

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// Declaring the capacity of the ByteBuffer

int capacity = 10;

// Creating the ByteBuffer

try {

// creating object of bytebuffer

// and allocating size capacity

ByteBuffer bb = ByteBuffer.allocate(capacity);

// putting the value in bytebuffer

bb.put((byte)10);

bb.put((byte)20);

bb.rewind();

// checking FloatBuffer fb is backed by array or not

boolean isArray = bb.hasArray();

// checking if else condition

if (isArray)

System.out.println("ByteBuffer bb is"

+ " backed by array");

else

System.out.println("ByteBuffer bb is"

+ " not backed by any array");

}

catch (IllegalArgumentException e) {

System.out.println("IllegalArgumentException catched");

}

catch (ReadOnlyBufferException e) {

System.out.println("ReadOnlyBufferException catched");

}

}

}

输出:

ByteBuffer bb is backed by array

范例2:当缓冲区由数组支持时

// Java program to demonstrate

// hasArray() method

import java.nio.*;

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// Declaring the capacity of the ByteBuffer

int capacity = 10;

// Creating the ByteBuffer

try {

// creating object of ByteBuffer

// and allocating size capacity

ByteBuffer bb = ByteBuffer.allocate(capacity);

// putting the value in ByteBuffer

bb.put((byte)8.56F);

bb.put((byte)10);

bb.rewind();

// Creating a read-only copy of ByteBuffer

// using asReadOnlyBuffer() method

ByteBuffer bb1 = bb.asReadOnlyBuffer();

// checking ByteBuffer bb is backed by array or not

boolean isArray = bb1.hasArray();

// checking if else condition

if (isArray)

System.out.println("ByteBuffer bb is"

+ " backed by array");

else

System.out.println("ByteBuffer bb is"

+ " not backed by any array");

}

catch (IllegalArgumentException e) {

System.out.println("IllegalArgumentException catched");

}

catch (ReadOnlyBufferException e) {

System.out.println("ReadOnlyBufferException catched");

}

}

}

输出:

ByteBuffer bb is not backed by any array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值