java.lang.reflect.Array.set() Method Example



Description

The java.lang.reflect.Array.set(Object array, int index, Object value) method sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type.

Declaration

Following is the declaration for java.lang.reflect.Array.set(Object array, int index, Object value) method.

public static void set(Object array, int index, Object value)
   throws IllegalArgumentException, ArrayIndexOutOfBoundsException

Parameters

  • array − the array.

  • index − the index.

  • value − the new value of the indexed component.

Exceptions

  • NullPointerException − If the specified object argument is null.

  • IllegalArgumentException − If the specified object argument is not an array, or if the array component type is primitive and an unwrapping conversion fails.

  • ArrayIndexOutOfBoundsException − If the specified index argument is negative, or if it is greater than or equal to the length of the specified array

Example

The following example shows the usage of java.lang.reflect.Array.set(Object array, int index, Object value) method.

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {

      String[] stringArray = (String[]) Array.newInstance(String.class, 3);

      Array.set(stringArray, 0, "Mahesh");
      Array.set(stringArray, 1, "Ramesh");
      Array.set(stringArray, 2, "Suresh");

      System.out.println("stringArray[0] = " + Array.get(stringArray, 0));
      System.out.println("stringArray[1] = " + Array.get(stringArray, 1));
      System.out.println("stringArray[2] = " + Array.get(stringArray, 2));
   }
}

Let us compile and run the above program, this will produce the following result −

stringArray[0] = Mahesh
stringArray[1] = Ramesh
stringArray[2] = Suresh
java_reflect_array.htm
Advertisements