I'm populating an arraylist in Java, and I'm wondering if it's possible to cuts some lines by doing the following (except complete):
myArraylist.add(new objectname varname (constructor things));
instead of:
objectname varname = new objectname(constructor things); myArrayList.add(varname);
CodePudding user response:
You can do the following (using a record as an example). But you won't have any other named instances of the created classes. Only the ones in the List.
record SomeClass(int arg1, int arg2){}
List<SomeClass> myArrayList =
new ArrayList<>(Arrays.asList(new SomeClass(1,2), new SomeClass(3,4), ...)));
Since Arrays.asList
returns a fixed size list you will need to pass it to an ArrayList
constructor to add more elements.