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 example, the first line has 3 elements, and the second line has 5 elements. How to do it in Java using Arraylist. Thanks.

+4
source share
9 answers

What about List<List<Foo>> ?

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); 
+3
source
 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 
+2
source

You can use an array for strings, since this restriction is fixed:

 @SuppressWarnings("unchecked") ArrayList<T>[] arr = new ArrayList[ fixedsize]; 

or use nested ArrayLists:

 List<List<T>> list = new ArrayList<List<T>>( fixedsize ); 
+2
source

Try:

 ArrayList<ArrayList<DataType>> array = new ArrayList<ArrayList<DataType>>(); for (int i = 0; i < n; ++i) { array.add(new ArrayList<DataType>()); } 
+1
source

As you say, you can create an arraylists array and use the ArrayList (int initial capacity) constructor to set the capacity of each column:

 ArrayList<YourObject>[] rows=new ArrayList<YourObjects>[n]; for(i=0;i<n;i++){ rows[i]=ArrayList<YourObjects>(initialsize); } 
0
source

You can create an array of ArrayList elements because your line count is fixed.

 ArrayList[] dynamicArray = new ArrayList[n](); 

Note. You will need to allocate an ArrayList object in each array entry. So that...

 for (int loop = 0; loop < n; loop++) dynamicArray[loop] = new ArrayList(); 

OR, if you want both rows and columns to be dynamic, you could create an ArrayList from ArrayLists ....

 ArrayList<ArrayList<T>> dynamicArray = new ArrayList<ArrayList<T>>(); 

Once again, you need to create a list of arrays in each new entry in dynamicArray.

0
source

if the row count is fixed, try something like this:

 ArrayList<MyObject>[] = new ArrayList<MyObject>[fixedRows] 
0
source
 List<ArrayList<SomeObject>> twoDList = new ArrayList<List<SomeObject>>(n); for( int i=0; i<n; i++ ) twoDList.add( new ArrayList<SomeObject>() ); 

Use as:

 twoDList.get(rownumber).add(newElementInColumn); 
0
source

I would create an ArrayList array (ArrayList [3] rows = new ArrayList [3] if there were 3 rows). Then, for each row, create column classes and paste them into an ArrayList. and then put the ArrayList in an array. the array array index can be used to track the row number. Remember that arrays start indexes at 0, so the number of rows will be equal to the rows [index + 1]

0
source

All Articles