Exploring Java Wildcards: When to Use Unbounded, Upper or Lower Bounded
In Java, a wildcard is a special syntax that allows you to specify a type parameter as "unknown" or "unspecified". It is denoted by the question mark character ?
and can be used in a few different ways.
The three main types of wildcards in Java are:
Unbounded Wildcard: The unbounded wildcard
?
can be used when you don't care about the type of elements in a collection. Here is an example:Copy codeList<?> list = new ArrayList<>(); list.add("foo"); // compilation error list.add(42); // compilation error
In the above example, we create a new List
objects with an unbounded wildcard. We can add any object to this list, but we can't add a specific type of object, such as a String
or an Integer
.
Upper Bounded Wildcard: The upper bounded wildcard
<? extends Type>
can be used when you want to accept a collection of objects that are all subtypes of a particular type. Here is an example:List<? extends Number> list = new ArrayList<>(); list.add(new Integer(42)); // compilation error list.add(new Double(3.14)); // compilation error
In the above example, we create a new
List
objects with an upper bounded wildcard. We specify that the elements in the list must be subtypes ofNumber
. We can add any subtype ofNumbers
, such asInteger
orDouble
, but we can't add aString.
Lower Bounded Wildcard: The lower bounded wildcard
<? super Type>
can be used when you want to accept a collection of objects that are all supertypes of a particular type. Here is an example:List<? super Integer> list = new ArrayList<>(); list.add(new Integer(42)); // OK list.add(new Number(3.14)); // compilation error
In the above example, we create a new
List
objects with a lower bounded wildcard. We specify that the elements in the list must be supertypes ofInteger
. We can add any supertype ofInteger
, such asNumber
orObject
, but we can't add aDouble
.Note that when using wildcards, you can't add anything to the list except for
null
. This is because the type of the list is not known at compile-time, so it's not safe to add any specific type of object.