java - Why can't the Integer.class object be added to a Collection<Class<Number>> object? -
this question has answer here:
i thought have quite understanding of generics can't figure out why compiler error here:
collection<class<number>> ncs = new hashset<class<number>>(); ncs.add(number.class); //ok! ncs.add(integer.class); //compiler error here
would nice if explain this. :)
edit: understand why it's not possible add integer.class
object collection> pointed out in this question. don't understand why example same. of course doesn't work:
collection<? extends number> ns = new hashset<number>(); ns.add(new integer(1)); //compiler error here
but does:
collection<number> ns = new hashset<number>(); ns.add(new integer(1)); //ok!
as far understand initial code uses same concepts.
given classes x
, y
, , z
, x
subclass of y
, x<z>
subclass of y<z>
(e.g. you've done collection
, hashset
), z<x>
not subclass of z<y>
, class<integer>
instance not class<number>
, can't put former in collection of latter. latter need wildcards, romeara has shown.
see this question.