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 List<List<Foo>>
?
For Example:
List<List<Foo>> list = new ArrayList<List<Foo>>();
List<Foo> row1 = new ArrayList<Foo>();
row1.add(new Foo());
row1.add(new Foo());
row1.add(new Foo());
list.add(row1);
List<Foo> row2 = new ArrayList<Foo>();
row2.add(new Foo());
row2.add(new Foo());
list.add(row2);
ArrayList<ArrayList<SomeObject>> twodlist = new ArrayList<ArrayList<SomeObject>>();
ArrayList<SomeObject> row = new ArrayList<SomeObject>();
row.add(new SomeObject(/* whatever */));
// etc
twodlist.add(row);
row = new ArrayList<SomeObject>();
// etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With