Nobodyknows2202 Nobodyknows2202 - 9 months ago 45
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());

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?


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 Source

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