United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: JDK-5092426 (coll) Collections.newSet() etc to avoid redundancy and concrete types
JDK-5092426 : (coll) Collections.newSet() etc to avoid redundancy and concrete types

Details
Type:
Enhancement
Submit Date:
2004-08-26
Status:
Closed
Updated Date:
2012-10-08
Project Name:
JDK
Resolved Date:
2011-07-25
Component:
core-libs
OS:
generic
Sub-Component:
java.util:collections
CPU:
generic
Priority:
P4
Resolution:
Won't Fix
Affected Versions:
5.0
Fixed Versions:

Related Reports
Relates:
Relates:

Sub Tasks

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
                                     
2011-07-25



Hardware and Software, Engineered to Work Together