-1

I thought to have a quite good understanding of generics but just can't figure out why I get a compiler error here:

    Collection<Class<Number>> ncs = new HashSet<Class<Number>>();               
    ncs.add(Number.class);      //ok!
    ncs.add(Integer.class);     //compiler error here

Would be nice if anyone could explain this. :)

Edit: I understand why it's not possible to add a Integer.class object to a Collection> as it is pointed out in this question. But I don't understand why my example is the same. Of course this doesn't work:

Collection<? extends Number> ns = new HashSet<Number>();
ns.add(new Integer(1)); //compiler error here

But this does:

Collection<Number> ns = new HashSet<Number>();
ns.add(new Integer(1)); //ok!

As far as I understand my initial code uses the same concepts.

Community
  • 1
  • 1
Morrandir
  • 595
  • 1
  • 4
  • 19

2 Answers2

3

Given classes X, Y, and Z, where X is a subclass of Y, X<Z> is a subclass of Y<Z> (e.g. what you've done with Collection and HashSet), but Z<X> is not a subclass of Z<Y>, so a Class<Integer> instance is not a Class<Number> and you can't put the former in a collection of the latter. For the latter you need wildcards, as romeara has shown.

See this question.

Community
  • 1
  • 1
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
2

I believe you need to declare the collection as

Collection<Class<? extends Number>> ncs = new HashSet<Class<? extends Number>>(); 

because of what Alex Hall explained in his answer:

Given classes X, Y, and Z, where X is a subclass of Y, X<Z> is a subclass of Y<Z>, but Z<X> is not a subclass of Z<Y>

romeara
  • 1,426
  • 1
  • 17
  • 26