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
...
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:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With