宣布多个arraylists

时间:2011-12-25 21:07:33

标签: java

是否可以在同一行中声明2个数组列表? e.g:

List<String> mm= new ArrayList<String>();
List<String> kk= new ArrayList<String>();

然后可以做类似的事情:

List<String> mm,kk= new ArrayList<String>();

显然,当我执行上述操作时出现编译错误,并且想知道如何在同一行中声明2个列表。

4 个答案:

答案 0 :(得分:8)

如果你想要,你应该这样做:

List<String> mm = new ArrayList<String>(), kk = new ArrayList<String>();

答案 1 :(得分:7)

简短回答:是的,你可以在同一个表达式中declare个2个变量。 List<String> mm,kk;宣布两个名单。

请注意,操作kk = new ArrayList<String>(); 不是声明,它是assigment

答案 2 :(得分:0)

您可以在同一行中声明它们,但无法初始化它们。 所以

List<String> mm,kk;

是可能的,但你仍然需要初始化它们

mm = new ArrayList<String>();
kk = new ArrayList<String>();

答案 3 :(得分:0)

What @fge wrote is the correct way. However make sure you don't initialize them in a single line like:

mm = kk = new ArrayList<String>();

as this would lead to both the lists pointing to the same arraylist object and would mess up both the lists.

This single line initialization can be done for primitive data types but not for reference data types.