Nobodyknows2202 Nobodyknows2202 - 23 days ago 9
Java Question

Java shorthand for function call on object initialization line

I often find myself needing a one time variable:

ArrayList<Object> alist = new ArrayList<Object>();
alist.add(new Object());
methodThatNeedsArrayList(alist);


Is it possible to write shorthand code like this:

methodThatNeedsArrayList(new ArrayList<Object>(){
this.add(new Object());
});


I find the first style of coding long and tedious. Is there any shorthand to accomplish this?

EDIT:

I ask for all of the Java language, not just for ArrayLists. Unlike the possible duplicate, answers will have more value for more people.

Answer

You can you use the double braces {{ notation:

methodThatNeedsArrayList(new ArrayList<Object>() {{
    add(new Object());
}});

but that creates an anonymous class. I'd prefer using streams:

methodThatNeedsArrayList(Stream.of(new Object()).collect(Collectors.toList())));
Comments