java 作为参数传递给 ArrayList 时,此处不允许使用数组初始值设定项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26039335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array initializer is not allowed here when passing as an argument to ArrayList
提问by Bala
I have some Model
classes that I am trying to declare a list with them but I get Array initializer is not allowed here
. What would be a simple work around?
我有一些Model
类,我试图用它们声明一个列表,但我得到Array initializer is not allowed here
. 什么是简单的解决方法?
...
public class M1 extends Model {}
public class M2 extends Model {}
...
List<Model> mObj = new ArrayList<Model>({M1, M2}) //expression expected
...
回答by ifloop
In Java 8you could make use of the Streams API:
在Java 8 中,您可以使用Streams API:
List<String> mObj = Stream.of("m1","m2","m3").collect(Collectors.toList());
Pre Java 8simply use:
Java 8 之前的版本只需使用:
List<Model> mObj = new ArrayList<>(Arrays.asList(m1, m2, m3));
For for information on this see:
有关这方面的信息,请参见:
回答by sol4me
You can use Arrays.asListwhich will return List<Model>
and then you can pass it to the constructor of ArrayList. Noteif you assign directly List
return by Arrays.asList
to List<Model>
then call to method like add()
will throw UnsupportedOperationException
because Arrays.asList return's AbstractList
您可以使用Arrays.asList它将返回List<Model>
,然后您可以将其传递给ArrayList的构造函数。请注意,如果您直接分配List
return by Arrays.asList
toList<Model>
然后调用方法 likeadd()
将抛出,UnsupportedOperationException
因为 Arrays.asList 返回的AbstractList
You should change
你应该改变
List<Model> mObj = new ArrayList<Model>({M1, M2}) //expression expected
to
到
List<Model> mObj = new ArrayList<Model>(Arrays.asList(M1, M2));
because constructor of class ArrayList
can take Collection<? extends Model>
因为类的构造函数ArrayList
可以Collection<? extends Model>