I want to create a 2D array that each cell is an ArrayList
!
I consider this defintions, but I can not add anything to themare these defintions true?!
ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>();
or
ArrayList[][] table = new ArrayList[10][10];//table.add??????
Please help me
Best Answer
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
The best way is to use a List
within a List
:
List<List<String>> listOfLists = new ArrayList<List<String>>();
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.
ArrayList<String>[][] list = new ArrayList[10][10];list[0][0] = new ArrayList<>();list[0][0].add("test");
This can be achieve by creating object of List data structure, as follows
List list = new ArrayList();
For more information refer this link
How to create a Multidimensional ArrayList in Java?