One of the small pieces of syntax sugar that many languages have is literals for lists and maps. How would these appear if we added them to Java?
The simplest syntax approach would be to copy what Groovy has already done.
List<String> list = ["Abba", "Beatles", "Corrs"]; List<String> emptyList = ;
This syntax is pretty clear and simple, creating an ArrayList (no opportunity to create a LinkedList etc.). The problems occur when you start considering the complications of generics.
The simple case is assignment, as shown above. Here, the generic type of the RHS would be inferred from the LHS without difficulty. However, if the literal isn't assigned to a variable then its a lot more complex.
["Abba", "Beatles", "Corrs"].add(new Date()); // compile error? .add(new Date()); // compile error?
The first option is to infer the generic type from the content of the list literal (common type shared between all elements). The second option is to use List<Object> in this case.
Verbose list literals
As an alternative syntax, we could use array literals as our syntax inspiration:
List<String> list = new ArrayList<String>() ["Abba", "Beatles", "Corrs"]; List<String> emptyList = new ArrayList<String>();
The advantage of this syntax is that the list implementation class and the generic type is clear. The disadvantage is the verbosity.
Map literals share exactly the same issues as list literals. The only difference is that maps have a key and a value. Again using Groovy as a basis, a colon would separate the key from the value:
// either with the short syntax Map<String, Integer> map = ["Abba" : 1972, "Beatles" : 1960, "Corrs" : 1995]; Map<String, Integer> emptyMap = [:]; // or using the verbose syntax Map<String, Integer> map = new HashMap<String, Integer>() ["Abba" : 1972, "Beatles" : 1960, "Corrs" : 1995];
List and map literals should be a really simple addition to Java. But they're not when you examine the detail. In this case, Java's static types and generics combine to cause difficulty.
Which of the two options (short or verbose) would I pick? To be honest, I don't know. Neither is exactly what I hoped for when I started writing this blog!
So, feedback welcomed on better alternatives!