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

北城余情 提交于 2019-12-17 04:53:35

问题


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


回答1:


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



回答2:


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

List<List<String>> listOfLists = new ArrayList<List<String>>();  



回答3:


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.




回答4:


ArrayList<String>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add("test");



回答5:


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?



来源:https://stackoverflow.com/questions/16956720/how-to-create-an-2d-arraylist-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!