Java Reference
In-Depth Information
type argument for the generic class type. In general, you might want to allow objects that are of types that
are subclasses of
T
to be added to a
BinaryTree<T>
object. Harking back to the
Person
and
Manager
classes
that you saw earlier, it might well be the case that you would want to add
Manager
objects and objects of
any subclass of
Person
to a
BinaryTree<Person>
container. You could accommodate this by redefining the
add()
method in the class as an independently parameterized method:
public <E extends T> void add(E value) {
if(root == null) { // If there's no root node
root = new Node(value); // store it in the root
} else { // Otherwise...
add(value, root); // add it recursively
}
}
Directory "TryParameterizedMethods"
Now the method has an independent type,
E
, for the method parameter. This type has an upper bound,
which in this case is the type parameter for
BinaryTree<T>
. Thus, you are saying here that the
add()
meth-
od accepts an argument of any type that is type
T
, or a subclass of
T
. This clearly adds flexibility to the use of
BinaryTree<T>
objects. You have no need to change the body of the method in this case. All the flexibility
is provided by the way you have defined the method parameter.
Of course, you must also alter the other version of the
add()
method that is defined in the
BinaryTree<>
class to have an independent parameter:
private <E extends T> void add(E value, Node node) {
int comparison = node.obj.compareTo(value);
if(comparison == 0) { // If it is equal to the current node
++node.count; // just increment the count
return;
}
if(comparison > 0) { // If it's less than the current node
if(node.left == null) { // and the left child node is null
node.left = new Node(value); // Store it as the left child node
} else { // Otherwise...
add(value, node.left); // ...add it to the left node
}
} else { // It must be greater than the current node
if(node.right == null) { // so it must go to the right...
node.right = new Node(value); // store it as the right node
} else { // ...or when right node is not null
add(value, node.right); // ...call add() again at the right node
}
}