英文:
is there a way to have a "main" arraylist?
问题
让我们假设我有
ArrayList<Citizen> citizen1 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen2 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen3 = new ArrayList<Citizen>();
是否可能拥有一个包含它们所有的 ArrayList?
英文:
Let's say I have
ArrayList<Citizen> citizen1 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen2 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen3 = new ArrayList<Citizen>();
is it possible to have an arraylist which compromise them all?
答案1
得分: 0
List<List<Citizen>> mainList = new ArrayList<>();
你可以使用 List of List<Citizens>。
还需要考虑以下几点。
我建议在创建列表对象时,左侧使用 "List"
而不是 "ArrayList"
。最好传递接口 "List"
,因为如果以后需要改为使用类似 Vector 的东西(例如,现在需要同步列表),您只需更改带有 "new" 语句的那一行。无论您使用哪种列表实现,例如 Vector 或 ArrayList
,您始终只传递 List<String>。
在 ArrayList 构造函数中,您可以将列表保留为空,它将默认为一定的大小,然后根据需要动态增长。但是,如果您知道您的列表可能有多大,有时可以节省一些性能。例如,如果您知道文件中总是会有 500 行,那么您可以这样做:
英文:
List<List<Citizen>> mainList= new ArrayList<>();
You can go with List of List<Citizens>.
Also need to consider below points.
I recommend using "List"
instead of "ArrayList"
on the left side when creating list objects. It's better to pass around the interface "List"
because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList
, you still always just pass around List<String>.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
答案2
得分: 0
你可以拥有一个公民(Citizen)的列表嵌套列表,就像这样:List<List<Citizen>> citizenList = new ArrayList<>()
;
你可以使用List
和Collection
的addAll()
方法,将另一个列表中的所有元素添加到一个列表中。
如果使用至少Java 8,你可以使用Streams API进行各种操作:Stream.of()
,Stream.concat()
,以及可能还有其他方法。
英文:
You can have a List of Lists of Citizen, like this: List<List<Citizen>>= new ArrayList<>()
;
You can use the addAll()
methods of List
and Collection
to add to one List all the elements of another list.
If using at least Java 8, you can do various things using the Streams API: Stream.of()
, Stream.concat()
, and maybe others.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论