Java Reference
In-Depth Information
return false;
} else {
int compare = value.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(root.left, value);
} else {
return contains(root.right, value);
}
}
}
You have to make one final change. Java knows only that these data values are of
some generic type
E
. As a result, the calls on
compareTo
in your
add
and
contains
methods generate compiler errors. You could fix this problem with a cast. For example,
you could replace the line:
int compare = value.compareTo(root.data);
with:
int compare = ((Comparable<E>) value).compareTo(root.data);
A better approach is to modify the class header to include this information. You
want to add the constraint that the class
E
implements the
Comparable
interface. You
specify that constraint by modifying the header as follows:
public class SearchTree<E extends Comparable<E>> {
...
}
It's odd that Java has you use the keyword
extends
because you want it to imple-
ment the interface, but that's how generics work in Java. If you are defining a class,
you make a distinction between the cases in which the new class extends another
class and those in which it implements an interface. But in generic declarations, you
use the word
extends
for both kinds of extension.
This is a fairly quick explanation of a complex topic. We don't have time to
explain the details of programming with generics in detail in this topic, although
there are many excellent online tutorials that you can find by entering “Java generics”
into your favorite web browser.
Search WWH ::
Custom Search