Java中的Array get()方法
java.lang.reflect.Array.get() 是Java中的一个内置方法,用于从指定的数组中返回给定索引处的元素。
语法
Array.get(Object []array, int index)
参数: 该方法接受两个必需的参数:
- array: 其索引将被返回的对象数组。
- index: 给定数组的特定索引。返回给定数组中的“index”处的元素。
返回值: 该方法返回数组元素作为Object类中的类型。
异常: 该方法抛出以下异常:
- NullPointerException - 当数组为null时。
- IllegalArgumentException - 当给定的对象数组不是数组时。
- ArrayIndexOutOfBoundsException - 如果给定的索引不在数组大小的范围内。
下面的程序演示了Array类的get()方法:
程序1:
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// 声明并定义一个int类型数组
int a[] = { 1, 2, 3, 4, 5 };
// 遍历数组
for (int i = 0; i < 5; i++) {
// Array.get方法
// 注意:强制类型转换是必要的
// 因为Object是返回类型。
int x = (int)Array.get(a, i);
// 输出值
System.out.print(x + " ");
}
}
}
1 2 3 4 5
程序2: 演示ArrayIndexOutOfBoundsException。
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// 声明并定义一个int类型数组
int a[] = { 1, 2, 3, 4, 5 };
try {
// 无效的索引
int x = (int)Array.get(a, 6);
System.out.println(x);
}
catch (Exception e) {
// 抛出异常
System.out.println("Exception : " + e);
}
}
}
Exception : java.lang.ArrayIndexOutOfBoundsException
程序3: 演示NullPointerException。
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// 声明一个int类型数组
int a[];
// 数组为null
a = null;
try {
// null对象数组
int x = (int)Array.get(a, 6);
System.out.println(x);
}
catch (Exception e) {
// 抛出异常
System.out.println("Exception : " + e);
}
}
}
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args)
{
// 声明一个String类型的数组
String[] arr = {"Hello", "World"};
try {
// 尝试获取数组中的元素,抛出异常
int x = (int)Array.get(arr, 1);
System.out.println(x);
}
catch (Exception e) {
// 抛出IllegalArgumentException异常
System.out.println("Exception : " + e);
}
}
}
Exception : java.lang.IllegalArgumentException
import java.lang.reflect.Array;
public class GfG {
// 主方法
public static void main(String[] args)
{
// int(不是数组)
int y = 0;
try {
// illegalArgument
int x = (int)Array.get(y, 6);
System.out.println(x);
}
catch (Exception e) {
// 抛出异常
System.out.println("Exception : " + e);
}
}
}
Exception : java.lang.IllegalArgumentException: Argument is not an array
极客教程