1. Technology
Send to a Friend via Email

Wildcard

By

Definition:

This glossary term for wildcard is in relation to Generics (you can also have wildcards in regular expressions).

With respect to Generics the wildcard is denoted by a question mark (i.e, ?) and it represent a type which is unknown; or it is a subclass or superclass of a defined type. Although Generics tries to tie down the object types for classes, interfaces and methods there are times when you want to be a little bit flexible.

Note: A wildcard cannot be used as a type for a generic method invocation, the creation of a generic class instance or a supertype.

There are three types of wildcards:

Upper Bounded Wildcards: Consider a method that works on a class and its subclasses. A good example is the class Number which has the subclasses Integer, Double and Float. You could define the method with an upper bounded wildcard:

public static void aMethod(List<? extends Number> list){
..
}

Here the wildcard is saying that the method can accept a List collection as long as it contains object of the Number type of any of the subclasses of Number class. Note the use of the extends keyword. This is a very flexible and powerful way of using Generics.

Of course, you still need to be careful how you treat the object types within the List collection. A subtype of a class might well have a method that its superclass does not. If you try to invoke that method when the collection contains the superclass objects there will be a runtime error.

UnBounded Wildcards: With unbounded wildcards what you are really saying is the type is unknown. This can be useful when you need to use the object class or the type parameter is irrelevant. For example, you might be using a method defined by the object class but want to accept any object type. Or you might have a method that wants to clear all the objects from a collection and in this case the type of the objects in the collection doesn't matter.

Lower Bounded Wildcards: Lower bounded wildcards are similar to the way upper bounded wildcards work. Instead of denoting the subclasses that apply the wildcard is denoting the superclasses. So, this time the method could be defined as:

public static void aMethod(List<? super Integer> list){
..
}

This time List collection could accept Integer types, Number types or Object types. This is because Number and Object are both superclasses of Integer. This time instead of the extends keyword we use the super keyword.

In the world of Generics, wildcards are a useful tool in still defining the types you are dealing with but with an added bit of flexibility.

Glossary:

# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. W
  6. Wildcard

©2014 About.com. All rights reserved.