Java 数组getBoolean()方法
java.lang.reflect.Array.getBoolean() 将指定数组中的给定索引作为一个短语返回。
语法:
Array.getBoolean(Object []array,int index)
参数
- array: 要返回其索引的对象数组。
- index: 给定数组的特定索引。在给定数组中位于’index’的元素被返回。
返回类型: 该方法返回数组中的元素为布尔值。
注意: 由于返回类型是布尔值,所以不需要进行类型转换。
异常: 该方法会抛出以下异常
- NullPointerException – 当数组为空时。
- IllegalArgumentException – 当给定的对象阵列不是一个数组时。
- ArrayIndexOutOfBoundsException – 如果给定的索引不在数组的大小范围内。
下面的程序说明了数组类的getBoolean()方法。
程序1 :
// Java code to demonstrate getBoolean() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining a boolean array
boolean a[] = {true,true,false};
// Traversing the array
for(int i = 0;i<3;i++){
// Array.getBoolean() method
boolean x = Array.getBoolean(a, i);
// Printing the values
System.out.print(x + " ");
}
}
}
输出。
true true false
计划2 :
// Java code to demonstrate getBoolean() method in Array
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining a boolean array
boolean a[] = {true,true,false};
try {
// invalid index
boolean x = Array.getBoolean(a, 6);
System.out.println(x);
} catch (Exception e) {
// throws Exception
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.ArrayIndexOutOfBoundsException
程序3 :
// Java code to demonstrate getBoolean() method in Array
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining a boolean array to null
boolean a[] = null;
try {
// null Object array
boolean x = Array.getBoolean(a, 6);
System.out.println(x);
} catch (Exception e) {
// throws Exception
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.NullPointerException
程序4 :
// Java code to demonstrate getBoolean() method in Array
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining a boolean variable
boolean a = true;
try {
// illegalArgument
boolean x = Array.getBoolean(a, 6);
System.out.println(x);
} catch (Exception e) {
// throws Exception
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.IllegalArgumentException: Argument is not an array
极客教程