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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:11:48  来源:igfitidea点击:

Array initializer is not allowed here when passing as an argument to ArrayList

java

提问by Bala

I have some Modelclasses 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 Listreturn by Arrays.asListto List<Model>then call to method like add()will throw UnsupportedOperationExceptionbecause Arrays.asList return's AbstractList

您可以使用Arrays.asList它将返回List<Model>,然后您可以将其传递给ArrayList的构造函数。请注意,如果您直接分配Listreturn by Arrays.asListtoList<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 ArrayListcan take Collection<? extends Model>

因为类的构造函数ArrayList可以Collection<? extends Model>