views:

1000

answers:

5

I am aware that you can initialize an array during instantiation as follows:

String[] names = new String[] {"Ryan", "Julie", "Bob"};

Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()?

Thanks,

Jonathan

+2  A: 

Well, in Java there's no literal syntax for lists, so you have to do .add().

If you have a lot of elements, it's a bit verbose, but you could either:

  1. use Groovy or something like that
  2. use Arrays.asList(array)

2 would look something like:

String[] elements = new String[] {"Ryan", "Julie", "Bob"};
List list = new ArrayList(Arrays.asList(elements));

This results in some unnecessary object creation though.

jayshao
+4  A: 

Yes.

new ArrayList<String>(){{
add("A");
add("B");
}}

What this is actually doing is creating a class derived from ArrayList<String> (the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this pointer. Not a problem unless you want to serialise it.

I understand that Java 7 will provide additional language constructs to do precisely what you want.

Brian Agnew
Downvoted why ?
Brian Agnew
Probably because people don't know this is possible. This is actually my favorite way to initialize maps and other more complex collections but for lists, i prefer Arrays.asList.
nicerobot
Not my downvote, but I consider this a pretty nasty abuse of anonymous classes. At least you're not trying to pass it off as a special feature...
Michael Borgwardt
Bad because it creates an anonymous class.
Steve Kuo
I don't believe that creating an anonymous class is bad *in itself*. You should be aware of it though.
Brian Agnew
+8  A: 

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
meriton
beat me to it :))
nc3b
It's worth mentioning that unless you strictly need an `ArrayList` it's probably better to just use the `List` that's returned by `Arrays#asList`.
maerics
+4  A: 

Here is the closest you can get:

ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));

You can go even simpler with:

List<String> list = Arrays.asList("Ryan", "Julie", "Bob")

Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):

ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")
Fred Haslam
The ArrayList constructed by asList is not a java.util.ArrayList, only shares the same. In fact, it cannot be, as the return value of asList is specified to be a fixed size list, but an ArrayList must be of variable size.
meriton
I stand corrected. I did not read far enough into the source.
Fred Haslam
+1  A: 

Arrays.asList("Ryan", "Julie", "Bob");

John D