What is the difference between Class<?> and Class<Object> in Java? AFAIK Java Erasure changes <?> to it's upper bound, which in this case would be Object anyway. So what is this for?
1 Answer
the difference is that Collection<String> is not a subtype of Collection<Object>, Collection<?> is usable in place as an argument where any collection can be put
17 Comments
aaronman
What is wrong with this
Adrian Shum
OP is asking for Class and you are answering with Collection, that's one problem. The other problem is, Collection<?> is not the supertype for all collections. I think you have misunderstanding wildcard in generics.
aaronman
aaronman
There is a quote in this article confirming what I said
Dima
@aaronman thats a good explanation, dont know who voted down for you... looks like Adrian Shum never programmed java....
|
Class<Object>be anything else thanObject.class. Mainly because it reminds me of the many, many questions that are of the form "I want to assign aList<String>to aList<Object>but Java won't let me." When writing code, you shouldn't primarily care what generics will erase to - the entire point of generics is to let the compiler do some type checks before they're erased.Class<?> cls = int.class;// CompilesClass<Object> cls2 = int.class;// Can't convert from Class<Integer> to Class<Object>It's a matter of what you can put into the variable.