当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Array getLong()用法及代码示例


java.lang.reflect.Array.getLong()是Java中的内置方法,用于从指定Array中以long形式返回给定索引处的元素。

句法

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

参数:此方法接受两个强制性参数:


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

返回值:此方法返回数组的元素。

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

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

以下示例程序旨在说明Array类的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.getLong method 
            long x = Array.getLong(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 
            // Array.getLong method 
            long x = Array.getLong(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 
            // Array.getLong method 
            long x = Array.getLong(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 
            // Array.getLong method 
            long x = Array.getLong(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


相关用法


注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 Array getLong() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。