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
参考资料: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#arrayOffset-