list literal gotcha and suggestion

Paul Benedict pbenedict at
Tue Sep 29 14:51:38 PDT 2009

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.


More information about the coin-dev mailing list