4

I am getting problems when generating a multi-dimensional array with unknown size. How can I fix it?

1
  • 3
    Can you show us what you have tried? Commented May 30, 2011 at 13:05

2 Answers 2

8

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>>();
Sign up to request clarification or add additional context in comments.

2 Comments

I am unable to use the following links for the above mentioned problem. javaprogrammingforums.com/collections-generics/…
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.
2

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

Hello Deepak, I have used ArrayList and with the following link. javaprogrammingforums.com/collections-generics/… but unable to run is successfully.
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]));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.