Java ShortBuffer hasArray()方法及示例
java.nio.ShortBuffer 类的 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 ShortBuffer
int capacity = 10;
// Creating the ShortBuffer
try {
// creating object of Shortbuffer
// and allocating size capacity
ShortBuffer sb = ShortBuffer.allocate(capacity);
// putting the value in Shortbuffer
sb.put((short)256);
sb.put(2, (short)91);
sb.rewind();
// checking ShortBuffer sb is backed by array or not
boolean isArray = sb.hasArray();
// checking if else condition
if (isArray)
System.out.println("ShortBuffer sb is"
+ " backed by array");
else
System.out.println("ShortBuffer sb is"
+ " not backed by any array");
}
catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException catched");
}
catch (ReadOnlyBufferException e) {
System.out.println("ReadOnlyBufferException catched");
}
}
}
输出:
ShortBuffer sb 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 ShortBuffer
int capacity = 10;
// Creating the ShortBuffer
try {
// creating object of Shortbuffer
// and allocating size capacity
ShortBuffer sb = ShortBuffer.allocate(capacity);
// putting the value in Shortbuffer
sb.put((short)856);
sb.put(2, (short)961);
sb.rewind();
// Creating a read-only copy of ShortBuffer
// using asReadOnlyBuffer() method
ShortBuffer sb1 = sb.asReadOnlyBuffer();
// checking ShortBuffer sb is backed by array or not
boolean isArray = sb1.hasArray();
// checking if else condition
if (isArray)
System.out.println("ShortBuffer sb is"
+ " backed by array");
else
System.out.println("ShortBuffer sb is"
+ " not backed by any array");
}
catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException catched");
}
catch (ReadOnlyBufferException e) {
System.out.println("ReadOnlyBufferException catched");
}
}
}
输出:
ShortBuffer sb is not backed by any array