I am getting problems when generating a multi-dimensional array with unknown size. How can I fix it?
2 Answers
To generate a multi-dimensional array with unknown size is called a jagged array.
For example:
String[][] array = new String[5][];
Java uses arrays of arrays for multi-dimensional arrays. I think you have to specify the first size. Otherwise, use list of lists.
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
2 Comments
Kumar Anil
I am unable to use the following links for the above mentioned problem. javaprogrammingforums.com/collections-generics/…
RMT
Then i do not think its impossible to be able to set a completly dynamic array you will have to use the first example provided.
Array is static. ArrayList is dynamic.
Before creating an array you should be aware of the size of the array. To create a multidimensional array without knowing array size is not possible.
Better you have to use a nested ArrayList or nested Vector:
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
2 Comments
Kumar Anil
Hello Deepak, I have used ArrayList and with the following link. javaprogrammingforums.com/collections-generics/… but unable to run is successfully.
kap
That is not true. You can generate each dimension on its own. This prints a nice triangle:
int dim1 = 6; int[][] array = new int[dim1][]; for (int i = 0; i < dim1; ++i) array[i] = new int[i + 1]; for (int i = 0; i < array.length; ++i) System.out.println(Arrays.toString(array[i]));