Java provides a powerful feature called Wildcards to handle generic types more flexibly. In this lesson, we'll focus on Unbounded Wildcards.
Unbounded wildcards, also known as ?, are used when you want to create a method or a field that can handle any type of object. They are called unbounded because they don't specify the type of the object.
List<?> list = new ArrayList<>(); // This list can hold any type of objectUnbounded wildcards are useful when you want to write a method that can handle any subtype of a specific type. This helps in writing more flexible and reusable code.
Let's consider a simple example of a method that accepts a list and returns the maximum element.
import java.util.List;
public class UnboundedWildcardsExample {
public static void main(String[] args) {
List<Integer> intList = List.of(1, 2, 3, 4, 5);
List<String> stringList = List.of("A", "B", "C", "D", "E");
System.out.println("Max Integer: " + getMax(intList));
System.out.println("Max String: " + getMax(stringList));
}
public static <T> T getMax(List<T> list) {
T max = list.get(0);
for (T element : list) {
if (element.compareTo(max) > 0) {
max = element;
}
}
return max;
}
}In this example, we have a method called getMax that accepts a generic list of type T. The list can contain any type of elements, and the method returns the maximum element in the list.
Unbounded wildcards are a powerful feature in Java that allows you to write more flexible and reusable code. They can handle any subtype of a specific type, making them useful in various scenarios.
In the next lesson, we'll explore Bounded Wildcards in more detail. Stay tuned! 🎯