Java 数组setShort()方法
java.lang.reflect.Array.setShort() 是Java中的一个内置方法,用于将一个指定的短值设置为一个给定对象数组的指定索引。
语法:
Array.setShort(Object []array,int index, short value)
参数: 该方法需要3个参数。
- array: 这是一个要被更新的对象类型的数组。
- index: 这是要被更新的数组的索引。
- value : 这是要在给定 数组 的给定 索引 上设置的短值。
异常: 该方法会抛出以下异常。
NullPointerException – 当数组为空时。
IllegalArgumentException – 当给定的对象数组不是一个数组。
ArrayIndexOutOfBoundsException – 如果给定的索引不在数组的大小范围内。
下面是Array.setShort()方法的实现。
程序1 :
// Java code to demonstrate
// setShort() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining Short array
short b[] = {1,2,3,4};
System.out.print("Before Set : ");
// printing the array
for(short x : b){
System.out.print(x + " ");
}
short value = 10;
// set method of class Array
Array.setShort(b, 1, value);
System.out.print("\nAfter Set : ");
// printing array
for(short x : b){
System.out.print(x + " ");
}
}
}
输出:
Before Set : 1 2 3 4
After Set : 1 10 3 4
程序2: 演示java.lang.NullPointerException
// Java code to demonstrate
// setShort() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining Short array to null
short b[] = null;
try{
short s = 10;
Array.setShort(b,5,s);
}
catch(Exception e){
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.NullPointerException
程序3: 演示java.lang.ArrayIndexOutOfBoundsException
// Java code to demonstrate
// setShort() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining Short array
short b[] = {1,2,3,4};
try{
short s = 10;
Array.setShort(b,5,s);
}
catch(Exception e){
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.ArrayIndexOutOfBoundsException
程序4: 演示java.lang.IllegalArgumentException
// Java code to demonstrate
// setShort() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining Short variable
short b = 1;
try{
short s = 10;
Array.setShort(b,5,s);
}
catch(Exception e){
System.out.println("Exception : " + e);
}
}
}
输出。
Exception : java.lang.IllegalArgumentException: Argument is not an array