开发者

Directly setting values for an ArrayList in Java

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 Arr开发者_运维问答ayList<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"); 
  ...
}}


Another option is to use Guava ("Google collections"), which has a Lists.newArrayList(...) method.

Your code would be something like

ArrayList<Integer> possibleValues2 = Lists.newArrayList(1,2,3,4,...);


From Java 7 SE docs:

List<Integer> possibleValues2 = Arrays.asList(1,2,3,4,5,6,7,8,9);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜