Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why collection literals?

From the various online articles on Java 7 I have come to know that Java 7 will be having collection literals1 like the following:

List<String> fruits = [ "Apple", "Mango", "Guava" ]; Set<String> flowers = { "Rose", "Daisy", "Chrysanthemum" }; Map<Integer, String> hindiNums = { 1 : "Ek", 2 : "Do", 3 : "Teen" };  

My questions are:

  1. Wouldn't it have been possible to provide a static method of in all of the collection classes which could be used as follows:

List<String> fruits = ArrayList.of("Apple", "Mango", "Guava");

IMO this looks as good as the literal version and is also reasonably concise. Why then did they have to invent a new syntax (EDIT: By 'new' I mean 'new to Java'.)?

  1. When I say List<String> fruits = [ "Apple", "Mango", "Guava" ]; what List would I actually get? Would it be ArrayList or LinkedList or something else?

1 As noted in the comments, collection literals did not make the cut for Java 7, nor indeed Java 8. (Here's an email from Brian Goetz, an Oracle developer, summarizing the rationale for not including this feature; and here is the proposal itself.)

like image 532
Green Hyena Avatar asked Apr 23 '10 17:04

Green Hyena


2 Answers

Answer to question 2:

final List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9]; 

gives you an immutable list.

The whole idea of this proposal that the subtype cannot be specified. The compiler chooses a suitable implementation depending on the collection on the right-hand side.

Read the details here: Proposal: Collection Literals

Answer to question 1: yes it would have. It's a matter of style.

like image 94
Eric Eijkelenboom Avatar answered Oct 08 '22 13:10

Eric Eijkelenboom


Another thing to note is that for lists this is very easy using var args, but have a little think about how you'd do it for a map. There is no way to supply pairs of arguments to a var args method, unless you introduce an extra Map.Entry object or something like that.

So using existing syntax you'd end up with

Map<String,String> map = HashMap.of( new Entry( "key1", "value1" ),                                       new Entry( "key2", "value2" ) ); 

which would get very tiring very quickly.

Even if you go down the path of using a builder pattern (as we do) then it's pretty ugly

Map<String,String> map = CollectionUtil.<String,String>map()                                         .put( "key1", "value1" )                                         .put( "key2", "value2" )                                         .map(); 
like image 41
Geoff Avatar answered Oct 08 '22 13:10

Geoff