Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D dynamic array using ArrayList in Java

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.

like image 506
user288609 Avatar asked Feb 24 '23 23:02

user288609


2 Answers

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);
like image 137
jmj Avatar answered Mar 02 '23 21:03

jmj


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
like image 30
MarioP Avatar answered Mar 02 '23 21:03

MarioP