Array initializer is not allowed here
I have several classes Model
that I am trying to declare with them, but I am getting Array initializer is not allowed here
. What would be a simple job?
...
public class M1 extends Model {}
public class M2 extends Model {}
...
List<Model> mObj = new ArrayList<Model>({M1, M2}) //expression expected
...
In Java 8, you can use the Streams API:
List<String> mObj = Stream.of("m1","m2","m3").collect(Collectors.toList());
Pre Java 8 just use:
List<Model> mObj = new ArrayList<>(Arrays.asList(m1, m2, m3));
For information on this see:
- Collectors
- Arrays.asList
You can use Arrays.asList that will return List<Model>
and then you can pass it to the ArrayList constructor . Note if you are assigning directly to List
return Arrays.asList
to List<Model>
then calling a method such as add()
will throw UnsupportedOperationException
because Arrays.asList returnsAbstractList
You must change
List<Model> mObj = new ArrayList<Model>({M1, M2}) //expression expected
to
List<Model> mObj = new ArrayList<Model>(Arrays.asList(M1, M2));
since the constructor of the class ArrayList
can takeCollection<? extends Model>