What are common mistakes developers make with bounded wildcards (? extends / ? super)?

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:

  • Misunderstanding the Concept: Developers can confuse the purpose of ? extends and ? super, leading to incorrect assumptions about how data can be added to or retrieved from collections.
  • Incorrect Usage in Method Signatures: Using bounded wildcards inappropriately in method parameters can lead to compile-time errors, especially in scenarios that involve adding elements to collections.
  • Overusing Wildcards: Excessive use of bounded wildcards can make code harder to read and maintain. Developers should strive for clarity and conciseness.
  • Failing to Leverage Covariance and Contravariance: Not fully understanding how covariance (with ? 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); } }

bounded wildcards ? extends ? super generics Java programming