Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compact syntax for instantiating an initializing collection

I'm looking for a compact syntax for instantiating a collection and adding a few items to it. I currently use this syntax:

Collection<String> collection =      new ArrayList<String>(Arrays.asList(new String[] { "1", "2", "3" })); 

I seem to recall that there's a more compact way of doing this that uses an anonymous subclass of ArrayList, then adds the items in the subclass' constructor. However, I can't seem to remember the exact syntax.

like image 957
Dónal Avatar asked Sep 22 '10 13:09

Dónal


People also ask

Can you instantiate a collection?

The Java Collection interface ( java. util. Collection ) is one of the root interfaces of the Java Collection API. Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often treat these subtypes uniformly as a Collection.


1 Answers

http://blog.firdau.si/2010/07/01/java-tips-initializing-collection/

List<String> s = Arrays.asList("1", "2"); 
like image 119
nanda Avatar answered Sep 21 '22 21:09

nanda