Creating array dynamically

In this post I will explain how to create array dynamically with an example.

This is useful when we don’t know the type of array until runtime.

Main code


1  package reflection;
2  
3  import java.lang.reflect.Array;
4  
5  public class ArraysDemo {
6   public static void main(String[] args) {
7       //Creating single dimension array
8       Object obj1 = Array.newInstance(Integer.class, 10);
9       for(int i = 0; i < 10; i++) {
10          Array.set(obj1, i, i);
11      }
12      for(int i = 0; i < 10; i++) {
13          System.out.println(Array.get(obj1, i));
14      }
15      System.out.println("");
16      //Creating multi dimension array
17      Integer[][] obj2 = (Integer[][])Array.newInstance(Integer.class, 2, 2);
18      for(int i = 0; i < 2; i++) {
19          for(int j = 0; j < 2; j++) {
20              obj2[i][j] = i;
21          }
22      }
23      for(int i = 0; i < 2; i++) {
24          for(int j = 0; j < 2; j++) {
25              System.out.print(obj2[i][j] + ",");
26          }
27          System.out.println("");
28      }
29  }
30 }

Explanation

In the above, at line 8 I create a one dimensional array by calling static method “newInstance” of Array class.

The method newInstance takes two parameters
1) The data type of the array
2) The dimension

At line 10 we call another static method named “set” to set the values of the array. This method takes three parameters
1) Array object
2) the index of the array indicating the location where the value has to be set
3) the value to be set

At line 13 we call another static method named “get” to get the value at a particular index in the array. This method takes two parameters
1) Array object
2) index

At line 17 we create a two dimensional array. The api doesn’t provide setter and getter methods similar to “set” and “get” method discussed above.

So we have to cast it to Integer array as we have done at line 17, then we can set or retrieve values in the usual manner.

Output

0
1
2
3
4
5
6
7
8
9

0,0,
1,1,

Leave a Reply