Difference between an unbound wildcard and a raw type

Sandeep Kumar picture Sandeep Kumar · Jan 9, 2013 · Viewed 8.4k times · Source

I was reading about generics and I did not understand the need for unbound wildcards and how it differs from raw type. I read this question but still did not get it clearly. In the Java tutorial page for unbound wildcard I got below two points and I did not understood first point:

  • If you are writing a method that can be implemented using functionality provided in the Object class.
  • When the code is using methods in the generic class that don't depend on the type parameter. For example, List.size() or List.clear(). In fact, Class<?> is so often used because most of the methods in Class<T> do not depend on T.

Can someone please explain the difference between unbound wildcard and raw type in layman language.

How does List<?> differ from List<Object>?

Answer

assylias picture assylias · Jan 9, 2013

How List<?> differs from List<Object>

The main difference is that the first line compiles but the second does not:

List<?> list = new ArrayList<String> ();
List<Object> list = new ArrayList<String> ();

However, because you don't know what the generic type of List<?> is, you can't use its parameterized methods:

List<?> list = new ArrayList<String> ();
list.add("aString"); //does not compile - we don't know it is a List<String>
list.clear(); //this is fine, does not depend on the generic parameter type

As for the difference with raw types (no generics), the code below compiles and runs fine:

List list = new ArrayList<String> ();
list.add("aString");
list.add(10);