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>
?
There are two scenarios where an unbounded wildcard is a useful approach: 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.
A raw type is the name of a generic class or interface without any type arguments.
There are three types of wildcards in Java which are Upper Bounded wildcards, Lower Bounded, and Unbounded wildcards.
both bounded and unbounded wildcards provide a lot of flexibility on API design especially because Generics is not covariant and List<String> can not be used in place of List<Object>. Bounded wildcards allow you to write methods that can operate on Collection of Type as well as Collection of Type subclasses.
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);
How List<?>
differs from List<Object>
?
List<Object> l1 = new ArrayList(); List<?> l2 = new ArrayList(); l1.add("Object"); //l2.add("Object"); incorrect l2.add(null);
You can only add null-value to the List<?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With