java bufferarray_Java Buffer arrayOffset()用法及代码示例

java.nio.Buffer类的arrayOffset()方法用于返回给定缓冲区的第一个元素的后备数组内的偏移量。

如果此缓冲区由数组支持,则缓冲区位置p对应于数组索引p + arrayOffset()。

在调用此方法之前,请先调用hasArray方法,以确保此缓冲区具有可访问的后备数组。

用法:

public abstract int arrayOffset()

返回值:此方法返回缓冲区第一个元素在此缓冲区数组内的偏移量

异常::如果此缓冲区由数组支持但为只读,则此方法引发ReadOnlyBufferException。

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

范例1:

// Java program to demonstrate

// arrayOffset() method

import java.nio.*;

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// Declaring the capacity of the ByteBuffer

int capacity = 4;

// Creating the ByteBuffer

try {

// creating object of ByteBuffer

// and allocating size capacity

ByteBuffer bb = ByteBuffer.allocate(capacity);

// putting the int to byte

// typecast value in ByteBuffer

bb.put((byte)20);

bb.put((byte)30);

bb.put((byte)40);

bb.put((byte)50);

// Typecasting ByteBuffer into Buffer

Buffer buffer = (Buffer)bb;

// offset within this buffer's array

// of the first element of the buffer

// using arrayOffset() method

int offset = buffer.arrayOffset();

// print the array

System.out.println("arrayOffset is : "

+ offset);

}

catch (ReadOnlyBufferException e) {

System.out.println("buffer is backed by an "

+ "array but is read-only");

System.out.println("Exception throws: " + e);

}

}

}

输出:

arrayOffset is : 0

范例2:对于ReadOnlyBufferException

// Java program to demonstrate

// arrayOffset() method

import java.nio.*;

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// Declaring the capacity of the ByteBuffer

int capacity = 4;

// Creating the ByteBuffer

try {

// creating object of ByteBuffer

// and allocating size capacity

ByteBuffer bb = ByteBuffer.allocate(capacity);

// putting the int to byte typecast

// value in ByteBuffer

bb.put((byte)20);

bb.put((byte)30);

bb.put((byte)40);

bb.put((byte)50);

// Creating a read-only copy of  ByteBuffer

// using asReadOnlyBuffer() method

ByteBuffer bb1 = bb.asReadOnlyBuffer();

// Typecasting read-only ByteBuffer

// into read-only Buffer

Buffer buffer = (Buffer)bb1;

// offset within this buffer's array

// of the first element of the buffer

// using arrayOffset() method

int offset = buffer.arrayOffset();

// print the array

System.out.println("arrayOffset is : "

+ offset);

}

catch (ReadOnlyBufferException e) {

System.out.println("buffer is backed by "

+ "an array but is read-only");

System.out.println("Exception throws: " + e);

}

}

}

输出:

buffer is backed by an array but is read-only

Exception throws: java.nio.ReadOnlyBufferException

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值