Setting a list of values for a Java ArrayList works:
Integer[] a = {1,2,3,4,5,6,7,8,9};
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList(a));
However, the following doesn't work and has the error "Illegal start of type" as well as other. Why not? Since the first line in the first code block is simply assignment, shouldn't it not have an effect?
ArrayList<Integer> possibleValues2 = new ArrayList<Integer>(Arrays.asList({1,2,3,4,5,6,7,8,9}));
You should use either the vararg version of Arrays.asList
, e.g.
ArrayList<Integer> possibleValues2 =
new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
or explicitly create an array parameter, e.g.
ArrayList<Integer> possibleValues2 =
new ArrayList<Integer>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9}));
A strange and little used idiom,
List<Integer> ints = new ArrayList<Integer>() {{add(1); add(2); add(3);}}
This is creating an anonymous class that extends ArrayList (outer brackets), and then implements the instance initializer (inner brackets) and calls List.add() there.
The advantage of this over Arrays.asList()
is that it works for any collection type:
Map<String,String> m = new HashMap<>() {{
put("foo", "bar");
put("baz", "buz");
...
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With