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.
? extends
WildcardThe ? 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: 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
}
}
? super
WildcardThe ? 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: 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
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?