9

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?

4
  • 2
    Intuitively, it feels wrong to have a Class<Object> be anything else than Object.class. Mainly because it reminds me of the many, many questions that are of the form "I want to assign a List<String> to a List<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. Commented May 5, 2013 at 23:29
  • I think this docs.oracle.com/javase/tutorial/java/generics/… explains it pretty well if I understood the question correctly. Commented May 5, 2013 at 23:35
  • possible duplicate of What is the difference between ? and Object in Java generics?. Also see Java: Different between List, List<?>, List<T>, List<E>, and List<Object> Commented May 6, 2013 at 3:28
  • Class<?> cls = int.class;// Compiles Class<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. Commented Jul 4, 2018 at 18:41

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

17 Comments

What is wrong with this
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.
There is a quote in this article confirming what I said
@aaronman thats a good explanation, dont know who voted down for you... looks like Adrian Shum never programmed java....
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.