Wildcards in Generics

by Karan Khanchandani.

Photo by Caspar Camille Rubin on Unsplash

In Generics, the ? called the wildcard, represents an Unknown type. We can see this wildcard being used in a various places like the type of parameter, field or local varidble, and sometimes as return type. The wildcard should never be used as a type argument for a generic method invocation, a generic class instance creation or a supertype.

A wildcard provides flexibility or restriction to the type parameter <T> in terms of what classes can be used in place of <T>. There are different types of wildcards.

Upper Bounded Wildcard

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number> ; you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ?, followed by the extends keyword and then followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either “extends” (as in classes) or “implements” (as in interfaces).

To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses.

The method for the above case will look like this

public static double sumOfList(List<? extends Number> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}

Lower Bounded Wildcard

As we saw above, an upper bounded wildcard restricts the unknown type to be a specific type or a subtype of that type and is represented using the extends keyword. In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.

A lower bounded wildcard is expressed using the wildcard character ?, following by the super keyword, followed by its lower bound.

Say, you want to write a method that puts Integer objects into a list. To maximize flexibility, you would like the method to work on List<Integer>, List<Number>, and List<Object> , anything that can hold Integer values.

To write the method that works on lists of Integer and the supertypes of Integer, such as Integer, Number, and Object, you would specify List<? super Integer>. The term List<Integer> is more restrictive than List<? super Integer> because the former matches a list of type Integer only, whereas the latter matches a list of any type that is a supertype of Integer.

A method that uses a lower bound may look like this.

public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
}

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.

Unbounded Wildcard

The unbounded wildcard type is specified using the wildcard character ?, for example, List<?>. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:

If you are writing a method that can be implemented using functionality provided in the Object class.

When the code is using methods in the generic class that don’t depend on the type parameter. For example, List.size or List.clear. In fact, Class<?> is so often used because most of the methods in Class<T> do not depend on T.

Consider the following method, printList:

public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}

The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. To write a generic printList method, use List<?>:

public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}

Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of any type:

List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);

It’s important to note that List<Object> and List<?> are not the same. You can insert an Object, or any subtype of Object, into a List<Object>. But you can only insert null into a List<?>.

Guidelines for using Wildcard

One of the more confusing aspects when learning to program with generics is determining when to use an upper bounded wildcard and when to use a lower bounded wildcard. This page provides some guidelines to follow when designing your code.

For purposes of this discussion, it is helpful to think of variables as providing one of two functions:

1. An “In” Variable An “in” variable serves up data to the code. Imagine a copy method with two arguments: copy(src, dest). The src argument provides the data to be copied, so it is the “in” parameter.

2. An “Out” Variable An “out” variable holds data for use elsewhere. In the copy example, copy(src, dest), the dest argument accepts data, so it is the “out” parameter.

Rules for using wildcard

1. An “in” variable is defined with an upper bounded wildcard, using the extends keyword.

2. An “out” variable is defined with a lower bounded wildcard, using the super keyword.

3. In the case where the “in” variable can be accessed using methods defined in the Object class, use an unbounded wildcard.

4. In the case where the code needs to access the variable as both an “in” and an “out” variable, do not use a wildcard.

These guidelines do not apply to a method’s return type. Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards.

A list defined by List<? extends …> can be informally thought of as read-only, but that is not a strict guarantee. Suppose you have the following two classes:

class NaturalNumber {    private int i;    public NaturalNumber(int i) { this.i = i; }
// ...
}class EvenNumber extends NaturalNumber { public EvenNumber(int i) { super(i); }
// ...
}

Consider the following code:

List<EvenNumber> le = new ArrayList<>();
List<? extends NaturalNumber> ln = le;
ln.add(new NaturalNumber(35)); // compile-time error

Because List<EvenNumber> is a subtype of List<? extends NaturalNumber>, you can assign le to ln. But you cannot use ln to add a natural number to a list of even numbers. The following operations on the list are possible:

* You can add null.

* You can invoke clear.

* You can get the iterator and invoke remove.

* You can capture the wildcard and write elements that you’ve read from the list.

* You can see that the list defined by List<? extends NaturalNumber> is not read-only in the strictest sense of the word, but you might think of it that way because you cannot store a new element or change an existing element in the list.

I hope you can now use wildcards with ease in your code. I have used the examples shown in Wildcards Oracle Documentation and Fun with Wildcards links. You can checkout the above links for more description on the topic.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store