06. Wildcards upper, lower and unbounded

Upper Bounded Wildcards

If we want our generic classes to accept multiple types that are related by a common superclass, we use upper bounded wildcards.

Let's learn this through an example. Suppose we have a method that adds two numbers together. We want the arguments to be some type of number, so we use the Number class, which is a superclass of Double, Integer, Float, Long, Short, etc.

We could try this...

public static double sum (ArrayList<Number> list) {
  double sum = 0;
  for (Number n : list) {
    sum += n.doubleValue();
  }
  return sum;
}

But notice that we can only place an array of the Number class here. We can't put in a type Double, Integer etc. because of how generic inheritance works.

To fix this, we can use the extends keyword with the wildcard symbol ?. So instead of ArrayList<Number>, we use ArrayList<? extends Number>. This means that this method is available to a class if any only if it extends the class Number.

Here's the updated code:
public static double sum (ArrayList<? extends Number> list) {
  double sum = 0;
  for (Number n : list) {
    sum += n.doubleValue();
  }
  return sum;
}

This is called using upper bounded wildcards, since the class Number serves as an upper bound for the types of classes we may use.

Lower Bounded Wildcards

For the reverse effect, we can use lower bounded wildcards.

If we wanted the opposite effect of upper bounded wildcards, we can use lower bounded wildcards.

<? super Integer> would specify the classes <Integer>, <Number> and <Object>.

Unbounded Wildcards

If we want to have it accept all type, we can have it extend Object, which every class in Java inherits from.

But instead of using <? extends Object> we can simplify this to <?>.

This code would print any type of object, no matter its type.
public static void printAnyObject(List<?> list) {
  for (Object item : list) {
    System.out.println(item);
  }
}

Learn Enterprise Java Development for a Bright Career

Java, A Beginner's Guide

Learn Enterprise Java Development for a Bright Career Try Java

A book that is simple, direct, terse with easy examples. Simple example programs to guide you as you go, with test exercises at the end for you to judge for yourself how well you understand the program. Learn java faster and efficiently with Java: A Beginner's Guide.

$ Check price
4040Amazon 4.5 logo(245+ reviews)

More Java resources

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Ad