Java中的Array getShort()方法

Java中的Array getShort()方法

Java中的数组类中有一个名为 java.lang.reflect.Array.getShort() 的内置方法,用于返回指定数组中给定索引处的元素作为short类型。

语法 :

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

参数:

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

返回类型: 这个方法将数组的元素作为short类型返回。

注: 因为返回类型是short,所以不需要强制类型转换。

异常: 下面是此方法抛出的异常:

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

下面的程序演示了数组类的getShort()方法:

程序1 :

// Java code to demonstrate getShort() method of Array class
import java.lang.reflect.Array;
public class GfG  {
    // main method
    public static void main(String[] args) {
           
       // Declaring and defining a short array
       short a[] = {1,2,3,4,5};
          
       // Traversing the array
       for(int i = 0;i<5;i++){
              
           // Array.getShort() method
              
           short x = Array.getShort(a, i);
           // Printing the values
           System.out.print(x + " ");
       }
           
    }
}
1 2 3 4 5

程序2 : 演示java.lang.ArrayIndexOutOfBoundsException。

// Java code to demonstrate getShort() method in Array
import java.lang.reflect.Array;
    
public class GfG {
    
    // main method
    public static void main(String[] args) {
        // Declaring and defining a short array
        short a[] = {1, 2, 3, 4, 5};
    
        try {
            // invalid index
            short x =  Array.getShort(a, 6);
            System.out.println(x);
        } catch (Exception e) {
            // throws Exception
            System.out.println("Exception : " + e);
        }
    }
}
Exception : java.lang.ArrayIndexOutOfBoundsException

程序3 : 演示java.lang.NullPointerException。

// Java code to demonstrate getShort() method in Array
import java.lang.reflect.Array;
    
public class GfG {
    
    // main method
    public static void main(String[] args) {
        // Declaring and defining a short array to null
        short a[] = null;
    
        try {
            // null Object Array
            short x =  Array.getShort(a, 6);
            System.out.println(x);
        } catch (Exception e) {
            // throws Exception
            System.out.println("Exception : " + e);
        }
    }
}
Exception : java.lang.NullPointerException

程序4 : 演示java.lang.IllegalArgumentException。

// Java代码,演示了Array中的getShort()方法
import java.lang.reflect.Array;
    
public class GfG {
    
    // 主方法
    public static void main(String[] args) {
        // 声明和定义一个short变量
        short a = 10;
    
        try {
            // 非法参数
            short x =  Array.getShort(a, 6);
            System.out.println(x);
        } catch (Exception e) {
            // 抛出异常
            System.out.println("异常:" + e);
        }
    }
}
异常:java.lang.IllegalArgumentException: Argument is not an array

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程