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
...
source to share
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>
source to share