Java Reference
In-Depth Information
Sorting a tree is not dependent on a specific type. You can call the sort() method without a cast because
the operation does not depend on a type argument. The method returns a LinkedList<> reference of a
specific type, LinkedList<Integer> in the first call and LinkedList<String> in the second, but the
lists array is of type LinkedList<?> so you can store references of any LinkedList<> type in it.
You list the sorted values stored in the lists that result from calls to the sort() method for the Bin-
aryTree<> objects in a loop:
for(LinkedList<?> list : lists){
System.out.println("\nSorted results:");
listAll(list);
}
The loop variable is of a wildcard type, LinkedList<?> , and it iterates over the elements in the
lists array. This is fine here because the static listAll() method does not require a particular
type of LinkedList<> reference as the argument; it works for LinkedList types created from the
LinkedList<> generic type using any type argument.
Note that you can create arrays of a generic type only using a wildcard specification that is unbounded.
If you specify an upper or lower bound for a wildcard type argument when defining an array type, it is
flagged by the compiler as an error.
PARAMETERIZED METHODS
You can define a method with its own independent set of one or more type parameters, in which case you
have a parameterized method , which is also referred to as a generic method . You can define parameterized
methods in an ordinary class. Methods within a generic type definition can also have independent type para-
meters.
You could modify the listAll() method that you defined in the TryWildcardArray class in the previ-
ous example so that it is a parameterized method. Here's how that would look:
public static <T> void listAll(LinkedList<T> list) {
for(T obj : list) {
System.out.println(obj);
}
}
The <T> following the public and static keywords is the type parameter list for the generic method.
Here you have only one type parameter, T , but you could have more. The type parameter list for a generic
method always appears between angled brackets and should follow any modifiers such as public and stat-
ic , as you have here, and should precede the return type.
Not that calling this version of the listAll() method does not require the type argument to be supplied
explicitly. The type argument is deduced from the type of the argument to the method when the method is
called. If you replace the listAll() code in the previous example by the version here, you should find that
it works just as well. No other changes to the program are necessary to make use of it.
You could also gain some advantage by using parameterized methods in the BinaryTree<> type defin-
ition. With the present version of this type, the add() method accepts an argument of type T , which is the
Search WWH ::




Custom Search