Java中的Array getInt()方法

Java中的Array getInt()方法

java.lang.reflect.Array.getInt() 是Java中的内置方法,用于将特定数组中指定索引处的元素作为整数返回。

语法:

Array.getInt(Object []array, int index)

参数: 该方法接受两个必选参数:

  • array: 需要返回其索引的对象数组。
  • index: 给定数组中的特定索引。返回给定数组中“index”处的元素。

返回值: 该方法将数组元素作为整数返回。

异常: 该方法引发以下异常:

  • NullPointerException - 当数组为NULL时。
  • IllegalArgumentException - 当给定的对象数组不是数组时。
  • ArrayIndexOutOfBoundsException - 如果给定的索引不在数组大小的范围内。

注意: 无需强制类型转换,因为返回类型是整数。

下面的程序说明了Array类的getInt()方法:

程序1:

import java.lang.reflect.Array;
  
public class GfG {
    // main method
    public static void main(String[] args)
    {
        // 声明和定义一个整形数组
        int a[] = { 1, 2, 3, 4, 5 };
  
        // 遍历数组
        for (int i = 0; i < 5; i++) {
  
            // Array.getInt方法
            int x = Array.getInt(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 a[] = { 1, 2, 3, 4, 5 };
  
        try {
            // 无效索引
            int x = Array.getInt(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)
    {
        // 声明一个整型数组
        int a[];
  
        // 将数组设为null
        a = null;
  
        try {
            // 空对象数组
            int x = Array.getInt(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 {
    // 主方法
    public static void main(String[] args)
    {
        // int(不是数组)
        int y = 0;
  
        try {
            // 非法参数
            int x = Array.getInt(y, 6);
  
            System.out.println(x);
        }
        catch (Exception e) {
            // 抛出异常
            System.out.println("Exception : " + e);
        }
    }
}
异常:java.lang.IllegalArgumentException:参数不是数组

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程