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);
  }
}

Take your Linux skills to the next level!

System Admin Handbook

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

This book approaches system administration in a practical way and is an invaluable reference for both new administrators and experienced professionals. It details best practices for every facet of system administration, including storage management, network design and administration, email, web hosting, scripting, and much more.

$ Check price
74.9974.99Amazon 4.5 logo(142+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Head First Java

Learn Enterprise Java Development for a Bright Career Try Java

Jump start your Java education with Head First Java! This book provides clean diagram examples, with text that is easy-to-understand in an almost too-casual language. Great for anyone new to Java or programming in general.

$ Check price
44.9544.95Amazon 4.5 logo(567+ reviews)

More Java resources

Ad