Array: get(Object array, int index) : Array « java.lang.reflect « Java by API






Array: get(Object array, int index)

  
import java.lang.reflect.Array;

public class Main {
  public static Object copyArray(final Object input) {
    final Class type = input.getClass();
    if (!type.isArray()) {
      throw new IllegalArgumentException();
    }
    final int length = Array.getLength(input);
    final Class componentType = type.getComponentType();

    final Object result = Array.newInstance(componentType, length);
    for (int idx = 0; idx < length; idx++) {
      Array.set(result, idx, Array.get(input, idx));
    }
    return result;
  }

  public static void main(final String[] args) {
    try {
      int[] x = new int[] { 2, 3, 8, 7, 5 };
      char[] y = new char[] { 'a', 'z', 'e' };
      String[] z = new String[] { "Jim", "John", "Joe" };
      System.out.println(" -- z and copy of z --");
      outputArrays(z, copyArray(z));
    } catch (final Exception ex) {
      ex.printStackTrace();
    }
  }


  public static void outputArrays(final Object first, final Object second) {
    if (!first.getClass().isArray()) {
      throw new IllegalArgumentException("first is not an array.");
    }
    if (!second.getClass().isArray()) {
      throw new IllegalArgumentException("second is not an array.");
    }

    final int lengthFirst = Array.getLength(first);
    final int lengthSecond = Array.getLength(second);
    final int length = Math.max(lengthFirst, lengthSecond);

    for (int idx = 0; idx < length; idx++) {
      System.out.print("[" + idx + "]\t");
      if (idx < lengthFirst) {
        System.out.print(Array.get(first, idx) + "\t\t");
      } else {
        System.out.print("\t\t");
      }
      if (idx < lengthSecond) {
        System.out.print(Array.get(second, idx) + "\t");
      }
      System.out.println();
    }
  }
}

   
    
  








Related examples in the same category

1.Array: clone()
2.Array: getInt(Object array, int index)
3.Array: getLength(Object array)
4.Array: newInstance(Class componentType, int length)
5.Array: newInstance(Class componentType, int... dimensions)
6.Array: set(Object array, int index, Object value)
7.Array: setInt(Object array, int index, int i)
8.Array: setLong(Object array, int index, long l)
9.Array: setShort(Object array, int index, short s)