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 and List, it can be of any other type of Object List argument to UnboundWildcardPrint method.
Unbounded wildcard is equivalent to .

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, List, List, and List. We can do this by using an upper bound wildcard as follows:

Public static void sum(List)

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 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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments