Java中的数组get()方法

这个 JAVA朗,反思一下。大堆得到() 是Java中的内置方法,用于从指定数组返回给定索引处的元素。

null

语法

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

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

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

返回值: 此方法将数组的元素作为对象类的类型返回。

例外情况: 此方法引发以下异常:

  • 空指针异常 –当数组为空时。
  • 非法数据异常 –当给定的对象数组不是数组时。
  • 数组下标越界异常 –如果给定索引不在数组大小的范围内。

下面的程序演示了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.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: 证明非法辩论的例外。

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

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享