Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

...
public class M1 extends Model {}
public class M2 extends Model {}

...
List<Model> mObj = new ArrayList<Model>({M1, M2}) //expression expected
...
like image 654
Bala Avatar asked May 30 '26 01:05

Bala


2 Answers

In Java 8 you could make use of the Streams API:

List<String> mObj = Stream.of("m1","m2","m3").collect(Collectors.toList());

Pre Java 8 simply use:

List<Model> mObj = new ArrayList<>(Arrays.asList(m1, m2, m3));


For for information on this see:

  • Collectors
  • Arrays.asList
like image 170
ifloop Avatar answered Jun 01 '26 16:06

ifloop


You can use Arrays.asList which will return List<Model> and then you can pass it to the constructor of ArrayList. Note if 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

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>

like image 43
sol4me Avatar answered Jun 01 '26 14:06

sol4me



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!