Posted by & filed under Code Tips.

Came across this the other day on Stack Overflow. Turns out there is a way to one line create an ArrayList and fill it all at the same time.

ArrayList<Integer> lst = new ArrayList<Integer>() {{
   add(1);
   add(2);
}};

It looks odd, mostly because that’s the first time I’d come across it. But it’s the same as doing this.

ArrayList<Integer> lst = new ArrayList<>();
lst.add(1);
lst.add(2);

One slight technical difference. The double braces creates an anonymous inner class to fill. Not sure if what cases that would matter though.

Also played a bit today and found that you have to specify the data type on both sides of the declaration. Feels weird to put Integer in both sets of <>.

Leave a Reply

Your email address will not be published. Required fields are marked *