I would not use this idiom to "simplify" ArrayList
declarations. It looks cool, but it needlessly creates an anonymous subclass of ArrayList
, and it looks too "magical" for my tastes... You want code that is both readable and understandable by the next developer.
You should instead consider using a library such as Google Guava.
Here is an example using Guava's Lists.newArrayList(E... elements) utility method:
import com.google.common.collect.Lists;
List<ArrayList<Integer>> numbers = Lists.newArrayList(
Lists.newArrayList(1, 2),
Lists.newArrayList(3, 4)
);
Or, even better, using only the List
interface on the left-hand side (you should avoid using concrete classes in your variable declarations):
import com.google.common.collect.Lists;
List<List<Integer>> numbers = Lists.<List<Integer>>newArrayList(
Lists.newArrayList(1, 2),
Lists.newArrayList(3, 4)
);
If you know these lists will be immutable, it's even better to use ImmutableList:
import com.google.common.collect.ImmutableList;
List<List<Integer>> numbers = ImmutableList.<List<Integer>>of(
ImmutableList.of(1, 2),
ImmutableList.of(3, 4)
);
> numbers = new ArrayList
– Heisenbug May 26 '11 at 19:03>(){add(Arrays.asList(1,2)),add(Arrays.asList(3,4))}; is that possible?