简体   繁体   English

定义一个2D ArrayList,其中包含多个ArrayList

[英]Defining a 2D ArrayList with multiple ArrayLists inside

ArrayList<ArrayList<String>, ArrayList<String>, ArrayList<String>> newlist = new ArrayList<ArrayList<String>, ArrayList<String>, ArrayList<String>>();

Above is my horrible ArrayList definition. 上面是我可怕的ArrayList定义。 I am trying to define an ArrayList containing multiple ArrayList inside although it gives me an Incorrect number of arguments error. 我试图定义一个ArrayList含有多种ArrayList虽然它给了我一个内部Incorrect number of arguments的错误。

facilities = {
 [parking]
 [bike]
 [disability]
}

I am trying to make an ArrayList to hold this data above The main ArrayList (Facilities) will contain the inner ArrayLists . 我正在尝试制作一个ArrayList来保存上面的数据。主ArrayList (设施)将包含内部ArrayLists What is the correct way to define an ArrayList of ArrayList s? 定义ArrayListArrayList的正确方法是什么?

First, ArrayList has only one type parameter, the type of all objects it contains, not each individual object. 首先, ArrayList只有一个类型参数,即它包含的所有对象的类型,而不是每个单独的对象。 Second, an ArrayList is not the correct choice for storing related data that should be in its own object. 其次,对于要存储在其自己对象中的相关数据, ArrayList不是正确的选择。

Fixing just the first problem would result in you defining your ArrayList as: 仅解决第一个问题将导致您将ArrayList定义为:

ArrayList<ArrayList<String>>

Additionally, usually you would program to the interface and define the variable as 另外,通常您将对接口进行编程并将变量定义为

List<List<String>>

You are free to use ArrayList or any other list as concrete implementations, of course, eg: 您可以自由使用ArrayList或任何其他列表作为具体实现,例如:

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

The second thing to fix would be to create a Facility class to encapsulate parking, bike, and disability. 要解决的第二件事是创建一个Facility类来封装停车,自行车和残障。 Then your list to hold Facility objects becomes simply: 然后,用于保存Facility对象的列表将变得简单:

List<Facility> newList = new ArrayList<>();

You use: 你用:

ArrayList<ArrayList<String>> array = new ArrayList<>();
array.add(//Your arrayList here);

You add ArrayList s to it just like you would String s to a regular ArrayList of String s. 您添加ArrayList就像你一样将它String s到一个普通ArrayListString秒。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM