How do you use bounded wildcards (? extends / ? super) with a simple code example?

In Java, bounded wildcards allow you to specify a range of types that can be used in a generic class or method. The two main types of bounded wildcards are ? extends T and ? super T. These can be particularly useful when you're working with collections.

Using ? extends Wildcard

The ? extends wildcard is used when you want to refer to an unknown subtype of a specific type. This is particularly useful for getting items from a structure, as it allows you to define a read-only access for the collection.

Example:

// Example: Using ? extends import java.util.ArrayList; import java.util.List; public class BoundedWildcardExample { public static void printList(List extends Number> list) { for (Number num : list) { System.out.println(num); } } public static void main(String[] args) { List integerList = new ArrayList<>(); integerList.add(1); integerList.add(2); printList(integerList); // Accepts List of Integer } }

Using ? super Wildcard

The ? super wildcard is used when you want to refer to an unknown supertype of a specific type. This is useful when you want to write items into a structure, as it allows you to provide a write access for the collection.

Example:

// Example: Using ? super import java.util.ArrayList; import java.util.List; public class BoundedWildcardExample { public static void addNumbers(List super Integer> list) { list.add(1); list.add(2); } public static void main(String[] args) { List numberList = new ArrayList<>(); addNumbers(numberList); // Accepts List of Number } }

keywords: Java bounded wildcards ? extends ? super generics collections