Previous | Next | Trail Map | The Reflection API | Working with Arrays

Creating Arrays

If you are writing a development tool such as an application builder, you may want to allow the end user to create arrays at runtime. Your program can provide this capability by invoking the Array.newInstance method.

The following sample program uses the newInstance method to create a copy of an array that is twice the size of the original array. The newInstance method accepts as arguments the length and component type of the new array. The source code follows:

import java.lang.reflect.*;

class SampleCreateArray {

   public static void main(String[] args) {
      int[] originalArray =  {55, 66};
      int[] biggerArray = (int[]) doubleArray(originalArray);
      System.out.println("originalArray:");
      for (int k = 0; k < Array.getLength(originalArray); k++)
         System.out.println(originalArray[k]);
      System.out.println("biggerArray:");
      for (int k = 0; k < Array.getLength(biggerArray); k++)
         System.out.println(biggerArray[k]);
   }

   static Object doubleArray(Object source) {
      int sourceLength = Array.getLength(source);
      Class arrayClass = source.getClass();
      Class componentClass = arrayClass.getComponentType();
      Object result = Array.newInstance(componentClass, sourceLength * 2);     
      System.arraycopy(source, 0, result, 0, sourceLength);
      return result;
   }
}

The output of the preceding program is:
originalArray:
55
66
biggerArray:
55
66
0
0
You can also use the newInstance method to create multidimensional arrays. In this case, the parameters of the method are the component type and an array of int types representing the dimensions of the new array.

The next sample program shows how to use newInstance to create multidimensional arrays:

import java.lang.reflect.*;

class SampleMultiArray {

   public static void main(String[] args) {

      // The oneDimA and oneDimB objects are one 
      // dimensional int arrays with 5 elements.

      int[] dim1 = {5};
      int[] oneDimA = (int[]) Array.newInstance(int.class, dim1);
      int[] oneDimB = (int[]) Array.newInstance(int.class, 5);

      // The twoDimStr object is a 5 X 10 array of String objects.

      int[] dimStr = {5, 10};
      String[][] twoDimStr = 
                 (String[][]) Array.newInstance(String.class,dimStr);

      // The twoDimA object is an array of 12 int arrays. The tail
      // dimension is not defined. It is equivalent to the array 
      // created as follows:
      //    int[][] ints = new int[12][];

      int[] dimA = {12};
      int[][] twoDimA = (int[][]) Array.newInstance(int[].class, dimA);
   }
}


Previous | Next | Trail Map | The Reflection API | Working with Arrays