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
This question is related to
java
arraylist
multidimensional-array
The best way is to use a List
within a List
:
List<List<String>> listOfLists = new ArrayList<List<String>>();
ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");
1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
should be written
List<List<String>> listOfLists = new ArrayList<List<String>>(size);
Then you will have to instantiate all columns of your 2d array
for(int i = 0; i < size; i++) {
listOfLists.add(new ArrayList<String>());
}
And you will use it like this :
listOfLists.get(0).add("foobar");
But if you really want to "create a 2D array that each cell is an ArrayList!"
Then you must go the dijkstra way.
This can be achieve by creating object of List data structure, as follows
List list = new ArrayList();
For more information refer this link
Source: Stackoverflow.com