JDK-5092426 : (coll) Collections.newSet() etc to avoid redundancy and concrete types
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: generic
  • CPU: generic
  • Submitted: 2004-08-26
  • Updated: 2012-10-08
  • Resolved: 2011-07-25
Related Reports
Relates :  
Relates :  
Description
Generified code that uses collections ends up writing this sort of thing all over the place:
    Set<String> strings = new HashSet<String>();
or even:
    Map<String,List<ObjectName>> map = new HashMap<String,List<ObjectName>>();

Having to duplicate the type parameters in the variable declaration and the constructor invocation is tedious and error-prone.  This could be greatly improved by the addition of methods like this to java.util.Collections:

    public static <T> Set<T> newSet() {
        return new HashSet<T>();
    }

and likewise for List, Map, SortedSet, and SortMap.  Now you can write:

    Map<String,List<ObjectName>> map = Collections.newMap();

The compiler's type inference allows it to know what kind of Map<K,V> to return here, just as it does for the existing Collections.emptyMap() method.  The specification should guarantee that the returned object serializes as a HashMap but probably does not need to say that it actually is a HashMap.

Another big advantage of these new methods would be that programmers would no longer need to learn that the canonical implementations of Set List Map SortedSet SortMap are HashSet ArrayList HashMap TreeSet TreeMap, as if they were verb conjugations.  ("I can't remember if the past tense of SortedSet is HashSet, TreeSet, or ArraySet.")  These concrete implementations would then only be of interest for serialization or for programmers who imagine they can improve the performance of their programs by supplying an initialCapacity to the constructor of HashSet etc.

Ideally there would also be versions of the "copy constructors" for the various types, though that ends up meaning a lot of methods, e.g.:
    public static <K,V> SortedMap<K,V> newSortedMap();
    public static <K,V> SortedMap<K,V> newSortedMap(Comparator<? super K>);
    public static <K,V> SortedMap<K,V> newSortedMap(Map<? extends K,? extends V>);
    public static <K,V> SortedMap<K,V> newSortedMap(SortedMap<K,? extends V>);

Comments
EVALUATION Java 7 Adds diamond operator to reduce duplication and redundancy
25-07-2011