Java Reference
In-Depth Information
Let's examine arraysEqual( ) closely. First, notice how it is declared by this line:
The type parameters are declared before the return type of the method. Also note that T
extends Comparable<T> . Comparable is an interface declared in java.lang . A class that
implements Comparable defines objects that can be ordered. Thus, requiring an upper
bound of Comparable ensures that arraysEqual( ) can be used only with objects that are
capable of being compared. Comparable is generic, and its type parameter specifies the
type of objects that it compares. (Shortly, you will see how to create a generic interface.)
Next, notice that the type V is upper-bounded by T . Thus, V must be either the same as
type T or a subclass of T . This relationship enforces that arraysEqual( ) can be called only
with arguments that are comparable with each other. Also notice that arraysEqual( ) is
static, enabling it to be called independently of any object. Understand, though, that gener-
ic methods can be either static or nonstatic. There is no restriction in this regard.
Now, notice how arraysEqual( ) is called within main( ) by use of the normal call syn-
tax, without the need to specify type arguments. This is because the types of the arguments
are automatically discerned, and the types of T and V are adjusted accordingly. For ex-
ample, in the first call:
the element type of the first argument is Integer , which causes Integer to be substituted
for T . The element type of the second argument is also Integer , which makes Integer a
substitute for V , too. Thus, the call to arraysEqual( ) is legal, and the two arrays can be
compared.
Now, notice the commented-out code, shown here:
If you remove the comments and then try to compile the program, you will receive an error.
The reason is that the type parameter V is bounded by T in the extends clause in V 's de-
claration. This means that V must be either type T or a subclass of T . In this case, the first
argument is of type Integer , making T into Integer , but the second argument is of type
Search WWH ::




Custom Search