Java Reference
In-Depth Information
ent only class types, and not interface types, so you can use this when you want to specify any type, as long
as it's a class type.
Defining a Lower Bound
You can constrain a wildcard type specification by specifying that it is a superclass of a given type. In this
case you use the super keyword to define a lower bound for the wildcard. Here's an example:
public static void analyze(LinkedList<? super MyClass> list) {
// Code to do whatever with the list...
}
Here you are saying that the elements in the list that is passed as the argument to the analyze() method
must be of type MyClass , or of a type that MyClass extends or implements. This should ring a bell in re-
lation to the BinaryTree<T> generic type from earlier in this chapter. A wildcard that is a superclass of a
given type sounds like a good candidate for what you were looking for to make the BinaryTree<T> type
more flexible, and it would accept a type argument that possibly inherited an implementation of the Com-
parable<T> interface. You could modify the definition to the following to allow this:
public class BinaryTree<T extends Comparable<? super T>> {
// Details exactly as before...
}
The only change that you have made to the BinaryTree<> type is that you've changed the type parameter
for the Comparable<T> interface to a wildcard that is a superclass of T , the type parameter for Bin-
aryTree<> . The effect is to allow any type argument to be accepted that implements the Comparable<T> in-
terface or inherits an implementation of it. This should allow the BinaryTree<> type to be used with classes
such as the Manager class, which could not be used as a type argument in the previous BinaryTree<T> im-
plementation. Let's prove it.
TRY IT OUT: A More Flexible Binary Tree
You need the definition of the Person and Manager classes that you saw earlier. The Person class defin-
ition is the following:
public class Person implements Comparable<Person> {
public Person(String name) {
this.name = name;
}
Search WWH ::




Custom Search