Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-5092426

(coll) Collections.newSet() etc to avoid redundancy and concrete types

    Details

    • Type: Enhancement
    • Status: Closed
    • Priority: P4
    • Resolution: Won't Fix
    • Affects Version/s: 5.0
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:

      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>);

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                emcmanus Eamonn McManus
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:
                  Imported:
                  Indexed: