JDK-6245673 : (coll) Add a varargs constructor to the various Collection implementations
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 5.0,7
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2005-03-24
  • Updated: 2022-12-08
  • Resolved: 2017-06-03
Related Reports
Duplicate :  
Duplicate :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I propose, for most of the Collection implementations (eg. HashSet, TreeSet, LinkedList, ArrayList, etc) something like:

class HashSet<E> ... {
  public HashSet(E item, E ... items) {
    add(item);
    for (E e : items)
      add(e);
  }
  ...
}


JUSTIFICATION :
It's the best kind of syntactic sugar.  It's not too sweet and doesn't require any new syntax.  Collections often have only one or a few members, and they are kind of annoying to set up.  You can either do things verbosely (and therefore error-pronely) like this:

class Something {
  public static final Set<Something> someSomethings = new HashSet<Something>();
  static {
    someSomethings.add(Something.THING0);
    someSomethings.add(Something.THING1);
  }
}

...or you end up with kludges like in EnumSet<E>:

public static <E extends Enum<E>> EnumSet<E> of(E e)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3)
public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e4, E e5)

That is begging for varargification.  Granted, those are not constructors, but that's just an implementation detail of EnumSet.  Sets in general (and indeed, most Collections) would benefit from a varargs constructor.
###@###.### 2005-03-24 19:14:25 GMT

Comments
Covered by JEP 269 (JDK-8048330). http://openjdk.java.net/jeps/269
03-06-2017

EVALUATION One big problem with the suggested addition is a conflict with existing constructors, e.g. SortedSet(Comparator) becomes ambiguous. One could envision a static factory SortedSet.of(E ... es) but if there are constructors you have to figure out how to accomodate both kinds of initializations. How to create a SortedSet with a specified Comparator *and* specified contents? Yet another issue is if the type argument used is itself generic, e.g. when creating SortedSet<List<String>> interaction with varargs introduces arrays of generic types, and those don't work so well in Java. We don't have a lot of practical experience with generics + varargs, but it's possible that in future best practice will be to avoid them, and only use varargs with concrete types? *** (#1 of 1): [ UNSAVED ] ###@###.###
06-08-2005