Bounded wildcards in Java, such as ? extends
and ? super
, are powerful tools that provide flexibility in generic programming. However, developers often make common mistakes when using them. Below are some of these mistakes:
? extends
and ? super
, leading to incorrect assumptions about how data can be added to or retrieved from collections.? extends
) and contravariance (with ? super
) work can lead to runtime exceptions.Here’s a simple example demonstrating the correct usage of bounded wildcards:
// Example of using bounded wildcards in Java
public class BoundedWildcardExample {
public static void printNumbers(List extends Number> list) {
for (Number number : list) {
System.out.println(number);
}
}
public static void addIntegers(List super Integer> list) {
list.add(1);
list.add(2);
list.add(3);
}
}
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?