list literal gotcha and suggestion

Reinier Zwitserloot reinier at
Tue Sep 29 20:15:45 PDT 2009

Too wordy. As I said in my post, this would be fine if you could add  
static methods to interfaces.

If we can't do that there's still a workable alternative in what you  
suggest, though I wouldn't call them 'newList'. How about:

return list(set("foo", "bar", "baz"))

with list and set imported from Collections.

Biggest problem is java's lousy inferencing; often you need to  
override generics but you can't do that with a statically imported  
method. One of the reasons why List.of() is quite superior in my  

Immutability should be the default - if you want mutability, you can  
always wrap whatever you are building into a new ArrayList/new HashSet/ 
new HashMap. Also, the exact type is far less important for  
immutables, so it becomes less confusing to add a generic 'create Set'  
without requiring the calling out of the type explicitly.

  --Reinier Zwitserloot

On 2009/29/09, at 23:51, Paul Benedict wrote:

> Reinier, you showed an interesting example.
>>> new HashSet<>(["a", "b", "c"]);
> It immediately reminded me of:
> public static <T> List<T> java.util.Arrays.asList(T... a)
> Likewise, what if static utility methods were introduced into existing
> collection classes? It would fit nicely with the on-going JDK 7 effort
> (i.e, java.util.Objects) to add highly-requested utility methods.
> public class ArrayList {
>  public static <E> ArrayList<E> newList(E... o) {..}
> }
> public class LinkedList {
>  public static <E> LinkedList<E> newList(E... o) {..}
> }
> public class HashSet {
>  public static <E> HashSet<E> newSet(E... o) {..}
> }
> public class TreeSet {
>  public static <E> TreeSet<E> newSet(E... o) {..}
> }
> I don't have a good answer here for a HashMap/TreeMap, but at least
> 80% could be handled using this pattern. The two major benefits are
> (1) the type is clearly being called out and (2) immutability can be
> achieved by wrapping the return with Collections.unmodifiableXXX.
> Collections.unmodifableSet(TreeSet.newSet(1, 2, 3, 4, 5));
> This example is very readable to me, the type is visible, and
> (im)mutability is an option.
> Paul

More information about the coin-dev mailing list