I need to implement a 2D dynamic array. The number of rows is fixed, say n. But the number of columns for each row is not fixed and equivalent. For instance, the first row has 3 elements and the second row has 5 elements. How to do this in Java using Arraylist. Thanks.
How about For Example:
|
|||||||||
|
As you say, you can make an array of arraylists and use the ArrayList(int initial capacity) constructor to set the capacity of each column:
|
|||||||||||||||||
|
You can either use a array for the rows since this dimenstion is fixed:
or use nested ArrayLists:
|
|||||||||||||||||||||
|
I would create an array of ArrayList (ArrayList[3] rows = new ArrayList[3] if the rows were 3) Then for each row create column classes and insert them into an ArrayList. and then place the ArrayList into the Array. the row array's index can be used to keep track of the row number. Remember arrays start there indexes at 0 so the row number would be rows[index+1] |
|||
|
Use as:
|
|||
|
|
|||||||||
|
if the number of rows is fixed, try something like this:
|
|||||||||||||||||||||
|
You could create an array of ArrayList elements because your row count is fixed.
Note: You'll need to allocate an ArrayList object in each entry in the array. So...
OR if you'd like both rows and columns to be dynamic you could create an ArrayList of ArrayLists....
Once again, you'll need to create an array list in each new entry to dynamicArray. |
|||
|
Try:
|
|||||||||||||||||||||
|
Something[][] s = new Something[numRows][]
ands[0] = new Something[3]
? – Tedil Jun 3 '11 at 20:30