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:
- Wouldn’t it have been possible to provide a static method
ofin 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’.)?
- When I say
List<String> fruits = [ "Apple", "Mango", "Guava" ];whatListwould I actually get? Would it beArrayListorLinkedListor 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.)
Answer to question 2:
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.