有没有一种方法可以拥有一个“主”arraylist?

huangapple go评论65阅读模式
英文:

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&lt;Citizen&gt; citizen1 = new ArrayList&lt;Citizen&gt;();
ArrayList&lt;Citizen&gt; citizen2 = new ArrayList&lt;Citizen&gt;();
ArrayList&lt;Citizen&gt; citizen3 = new ArrayList&lt;Citizen&gt;();

is it possible to have an arraylist which compromise them all?

答案1

得分: 0

List<List<Citizen>> mainList = new ArrayList<>();

你可以使用 List of List<Citizens>。

还需要考虑以下几点。

我建议在创建列表对象时,左侧使用 &quot;List&quot; 而不是 &quot;ArrayList&quot;。最好传递接口 &quot;List&quot;,因为如果以后需要改为使用类似 Vector 的东西(例如,现在需要同步列表),您只需更改带有 "new" 语句的那一行。无论您使用哪种列表实现,例如 Vector 或 ArrayList,您始终只传递 List<String>。

在 ArrayList 构造函数中,您可以将列表保留为空,它将默认为一定的大小,然后根据需要动态增长。但是,如果您知道您的列表可能有多大,有时可以节省一些性能。例如,如果您知道文件中总是会有 500 行,那么您可以这样做:

英文:

List&lt;List&lt;Citizen&gt;&gt; mainList= new ArrayList&lt;&gt;();

You can go with List of List<Citizens>.

Also need to consider below points.

I recommend using &quot;List&quot; instead of &quot;ArrayList&quot; on the left side when creating list objects. It's better to pass around the interface &quot;List&quot; 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<>()

你可以使用ListCollectionaddAll()方法,将另一个列表中的所有元素添加到一个列表中。

如果使用至少Java 8,你可以使用Streams API进行各种操作:Stream.of()Stream.concat(),以及可能还有其他方法。

英文:

You can have a List of Lists of Citizen, like this: List&lt;List&lt;Citizen&gt;&gt;= new ArrayList&lt;&gt;();

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.

huangapple
  • 本文由 发表于 2020年8月28日 20:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63634114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定