waiwai933
waiwai933

Reputation: 14559

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

Upvotes: 16

Views: 72553

Answers (4)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

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"); 
  ...
}}

Upvotes: 9

appsunited
appsunited

Reputation: 1667

From Java 7 SE docs:

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

Upvotes: 0

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116266

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

Upvotes: 28

Uri
Uri

Reputation: 89749

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,...);

Upvotes: 4

Related Questions