Instantiating and populating a list or collection

In Java it always irks me when I have to create a collection and then populate it in separate steps as follows:

List states = new ArrayList();
state.add(State.CA);
state.add(State.WY);

Then today I read about using an anonymous subclass with instance initializer to initialize a collection which appeals to the block loving Rubyist in me:

List states = new ArrayList() {{ add(State.CA); add(State.WY); }};

Another approach shown to me by a new co-worker specific to Lists (that involves creating an extra array) but is also quite short is:

List states = Arrays.asList(new State[]{State.CA, State.WY});

Update: Ricky Clarkson pointed out the best solution so far in my opinion (requires JDK 5 or higher) using varargs and generics:

List<String> list=Arrays.asList("rocks","my","world");
This entry was posted in Java, Ruby, Software Engineering. Bookmark the permalink.

12 Responses to Instantiating and populating a list or collection

  1. Pingback: Daniel Schneller's Weblog

  2. Pingback: Java Tips: Initializing Collection « satukubik

  3. Pingback: Martial Java / Initializing Collection