A wildcard can be used as a type of a parameter, field, local variable, and return type. Question mark (?) wildcard in generics and it represents the unknown type.
Unbounded wildcard
When we want our generic type to be working with all types, an unbounded wildcard can be used.
For example:
class UnboundWildcard {
public static void UnboundWildcardPrint(List> list) {
list.forEach(listElement->{
System.out.println(listElement);
});
}
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
UnboundWildcardPrint(list);
List numbers = new ArrayList<>();
numbers.add(10);
numbers.add(50);
numbers.add(100);
UnboundWildcardPrint(numbers);
}
}
In the above example list parameter is provided as List
Unbounded wildcard is equivalent to Extends Object>.
Upper Bounded wildcard
This is useful when we want to relax the restriction on the type of parameter in a method. For example, we want to write a method, that works with List
Public static void sum(List extends Number>)
Lower Bound wildcard:
This is useful when we want to restrict the type of parameter in a method to it’s lower bound and it’s super class.
For example:
public static void sumIntegers(List super Integer> list)
In the above example, we can only pass Integer or Number (Super class of Integer). We can’t pass Double or Long, as they aren’t the Super class of Integer.