Java Unbounded Wildcards 🎯

beginner
17 min

Java Unbounded Wildcards 🎯

Java provides a powerful feature called Wildcards to handle generic types more flexibly. In this lesson, we'll focus on Unbounded Wildcards.

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

java
List<?> list = new ArrayList<>(); // This list can hold any type of object

Why use Unbounded Wildcards? 💡

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

Example of Unbounded Wildcards 🎯

Let's consider a simple example of a method that accepts a list and returns the maximum element.

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

Quiz 🎯

Conclusion 📝

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! 🎯