Java中的Array getLong()方法
java.lang.reflect.Array.getLong() 是Java中的内置方法,用于返回指定数组中给定索引的元素作为一个long值。
语法:
Array.getLong(Object []array, int index)
参数: 此方法接受两个必需参数:
- array: 要返回索引的对象数组。
- index: 给定数组中特定的索引。返回给定数组中“index”处的元素。
返回值: 此方法返回数组的元素,类型为long。
异常: 此方法可能抛出以下异常:
- NullPointerException - 当数组为空时。
- IllegalArgumentException - 当给定的对象数组不是数组时。
- ArrayIndexOutOfBoundsException - 如果给定的索引不在数组大小的范围内。
下面的程序示例了Array类的get()方法:
程序 1:
import java.lang.reflect.Array;
public class GfG {
// main方法
public static void main(String[] args)
{
// 声明和定义一个int数组
int a[] = { 1, 2, 3, 4, 5 };
// 遍历数组
for (int i = 0; i < 5; i++) {
// Array.getLong方法
long x = Array.getLong(a, i);
// 输出值
System.out.print(x + " ");
}
}
}
1 2 3 4 5
程序 2: 用于演示ArrayIndexOutOfBoundsException。
import java.lang.reflect.Array;
public class GfG {
// main方法
public static void main(String[] args)
{
// 声明和定义一个int数组
int a[] = { 1, 2, 3, 4, 5 };
try {
// 无效索引
// Array.getLong方法
long x = Array.getLong(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方法
public static void main(String[] args)
{
// 声明一个int数组
int a[];
// 把数组设置为null
a = null;
try {
// null对象数组
// Array.getLong方法
long x = Array.getLong(a, 6);
System.out.println(x);
}
catch (Exception e) {
// 抛出异常
System.out.println("Exception : " + e);
}
}
}
Exception : java.lang.NullPointerException
程序 4: 用于演示IllegalArgumentException。
import java.lang.reflect.Array;
public class GfG {
// 主方法
public static void main(String[] args)
{
// int(不是数组)
int y = 0;
try {
// illegalArgument
// Array.getLong方法
long x = Array.getLong(y, 6);
System.out.println(x);
}
catch (Exception e) {
// 抛出异常
System.out.println("异常:" + e);
}
}
}
异常:java.lang.IllegalArgumentException: Argument is not an array
极客教程