Java 数组get()方法
java.lang.reflect.Array.get() 是Java中的一个内置方法,用于返回指定数组中给定索引的元素。
语法
Array.get(Object []array, int index)
参数: 该方法接受两个强制性参数。
- array: 对象数组,其索引将被返回。
 - index: 给定数组的特定索引。在给定数组中位于 “index “的元素将被返回。
 
返回值: 该方法返回对象类型的数组中的元素。
异常: 该方法会抛出以下异常。
- NullPointerException – 当数组为空时。
 - IllegalArgumentException – 当给定的对象数组不是一个数组。
 - ArrayIndexOutOfBoundsException – 如果给定的索引不在数组的大小范围内。
 
下面的程序说明了数组类的get()方法。
程序1 :
import java.lang.reflect.Array;
  
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // Declaring and defining an int array
        int a[] = { 1, 2, 3, 4, 5 };
  
        // Traversing the array
        for (int i = 0; i < 5; i++) {
  
            // Array.get method
            // Note : typecasting is essential
            // as the return type in Object.
            int x = (int)Array.get(a, i);
  
            // Printing the values
            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)
    {
        // Declaring and defining an int array
        int a[] = { 1, 2, 3, 4, 5 };
  
        try {
            // invalid index
            int x = (int)Array.get(a, 6);
            System.out.println(x);
        }
        catch (Exception e) {
            // throws Exception
            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)
    {
        // Declaring an int array
        int a[];
  
        // array to null
        a = null;
  
        try {
            // null Object array
            int x = (int)Array.get(a, 6);
            System.out.println(x);
        }
        catch (Exception e) {
            // throws Exception
            System.out.println("Exception : " + e);
        }
    }
}
输出。
Exception : java.lang.NullPointerException
程序4: 演示IllegalArgumentException。
import java.lang.reflect.Array;
  
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // int (Not an array)
        int y = 0;
  
        try {
            // illegalArgument
            int x = (int)Array.get(y, 6);
  
            System.out.println(x);
        }
        catch (Exception e) {
            // Throws exception
            System.out.println("Exception : " + e);
        }
    }
}
输出。
Exception : java.lang.IllegalArgumentException: Argument is not an array
极客教程