Exploring Java Wildcards: When to Use Unbounded, Upper or Lower Bounded

In Java, a wildcard is a special syntax that allows you to specify a type parameter as "unknown" or "unspecified". It is denoted by the question mark character ? and can be used in a few different ways.

The three main types of wildcards in Java are:

  1. Unbounded Wildcard: The unbounded wildcard ? can be used when you don't care about the type of elements in a collection. Here is an example:

  2.  Copy codeList<?> list = new ArrayList<>();
     list.add("foo");  // compilation error
     list.add(42);     // compilation error
    

In the above example, we create a new List objects with an unbounded wildcard. We can add any object to this list, but we can't add a specific type of object, such as a String or an Integer.

  1. Upper Bounded Wildcard: The upper bounded wildcard <? extends Type> can be used when you want to accept a collection of objects that are all subtypes of a particular type. Here is an example:

     List<? extends Number> list = new ArrayList<>();
     list.add(new Integer(42));    // compilation error
     list.add(new Double(3.14));   // compilation error
    

    In the above example, we create a new List objects with an upper bounded wildcard. We specify that the elements in the list must be subtypes of Number. We can add any subtype of Numbers, such as Integer or Double, but we can't add a String.

  2. Lower Bounded Wildcard: The lower bounded wildcard <? super Type> can be used when you want to accept a collection of objects that are all supertypes of a particular type. Here is an example:

  3.  List<? super Integer> list = new ArrayList<>();
     list.add(new Integer(42));    // OK
     list.add(new Number(3.14));   // compilation error
    

    In the above example, we create a new List objects with a lower bounded wildcard. We specify that the elements in the list must be supertypes of Integer. We can add any supertype of Integer, such as Number or Object, but we can't add a Double.

  4. Note that when using wildcards, you can't add anything to the list except for null. This is because the type of the list is not known at compile-time, so it's not safe to add any specific type of object.