When should you prefer wildcards (?) and when should you avoid it?

In Java, wildcards (represented by the symbol "?") are used in generics to represent an unknown type. They can simplify code and make it more flexible, but they should be used with caution. Here's when to prefer wildcards and when to avoid them:

When to Prefer Wildcards

  • Flexibility: Use wildcards when you want to allow a method to accept arguments of various types without being too specific.
  • Read-only data: If you're only reading from a collection and not modifying it, wildcards can be useful. For instance, using "? extends T" allows you to work with any subtype of T.

When to Avoid Wildcards

  • Complexity: Using wildcards can sometimes make code harder to read and understand. If clarity is a priority, consider using concrete types.
  • Modification: Avoid wildcards when you need to add elements to a collection. For this, a specific type is preferable.

Example of Using Wildcards

class Box<T> { private List<T> items = new ArrayList<>(); public void add(T item) { items.add(item); } public void printItems() { for (T item : items) { System.out.println(item); } } } // Method using wildcards public static void printBoxItems(Box<? extends Number> box) { box.printItems(); }

Wildcards in Java Java Generics ? extends ? super Java Collections