[Haskell-cafe] Re: What I wish someone had told me...

Robert Greayer robgreayer at yahoo.com
Thu Oct 16 14:41:26 EDT 2008

--- On Thu, 10/16/08, Jonathan Cast <jonathanccast at fastmail.fm> wrote:

> But I can't say new HashSet<?>()?
No... but you can say 'new HashSet<T>()' where T is a type variable, and then put a value of type T into your set, which is probably generally what you want.  HashSet<?> is a set of unknown (at compile time) element type.  It is not safe to put any element into such a set.  Consider:

void wrong(List<?> foo, List<?> bar) {
   foo.add(bar.get(0)); // illegal... but if it weren't...

List<Integer> x = ...;
List<String> y = ...;
wrong(x, y); // then this would put an String into a list of ints...


Perhaps there was confusion over what you meant by 'conjure up a value of an unknown type'... you can't explicitly instantiate a parameterized class with a wildcard type variable (e.g. new HashSet<?>).  However, you can conjure up an instance of any class for which you have a Class object handy, provided it is non-abstract and has public constructors, and then assign it to a variable with a wildcard in its type.


More information about the Haskell-Cafe mailing list