Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an 2D ArrayList in java? [duplicate]

I want to create a 2D array that each cell is an ArrayList!

I consider this defintions, but I can not add anything to them are these defintions true?!

ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>(); 

or

ArrayList[][] table = new ArrayList[10][10];  //table.add?????? 

Please help me

like image 966
Rezan Avatar asked Jun 06 '13 08:06

Rezan


People also ask

How do you duplicate a 2D array?

A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

Can you make a 2D ArrayList in Java?

The next method to produce a 2D list in Java is to create an ArrayList of ArrayLists; it will serve our purpose as it will be two-dimensional. To insert an innerArraylist function inside outerArrayList1 , we can initialize the 2D ArrayList Java object to outerArrayList1 .

How do you repeat an ArrayList in Java?

An Iterator can be used to loop through an ArrayList. The method hasNext( ) returns true if there are more elements in ArrayList and false otherwise. The method next( ) returns the next element in the ArrayList and throws the exception NoSuchElementException if there is no next element.


2 Answers

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10]; table[0][0] = new ArrayList(); // add another ArrayList object to [0,0] table[0][0].add(); // add object to that ArrayList 
like image 75
AllTooSir Avatar answered Sep 22 '22 17:09

AllTooSir


The best way is to use a List within a List:

List<List<String>> listOfLists = new ArrayList<List<String>>();   
like image 37
PSR Avatar answered Sep 20 '22 17:09

PSR