Skip to content
Advertisement

In java, what’s the correct syntax for creating/constructing/defining a named variable on the same line as I add it to an arraylist?

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);

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement