Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly setting values for an ArrayList in Java

Tags:

java

arraylist

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}));
like image 242
waiwai933 Avatar asked Jan 21 '11 21:01

waiwai933


2 Answers

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}));
like image 150
Péter Török Avatar answered Sep 20 '22 17:09

Péter Török


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"); 
  ...
}}
like image 41
Jeffrey Blattman Avatar answered Sep 19 '22 17:09

Jeffrey Blattman