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()
orList.clear()
. In fact,Class<?>
is so often used because most of the methods inClass<T>
do not depend onT
.
Can someone please explain the difference between unbound wildcard and raw type in layman language.
How does List<?>
differ from List<Object>
?
How
List<?>
differs fromList<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);