Java Reference
In-Depth Information
aryTree<Double> , or indeed any BinaryTree<> type. To make this clearer, let's consider a specific situ-
ation where you might use a wildcard as an argument for a method parameter of a generic type.
In the previous example, the main() method listed the objects in the LinkedList<> object that the
sort() method returns by executing a specific loop for each of the two cases — Integer objects and
String objects. You could write a static method that would list the items stored in a linked list, whatever
they are. Here's how you could define such a method as a static member of the TryBinaryTree class:
public static void listAll(LinkedList<?> list) {
for(Object obj : list) {
System.out.println(obj);
}
}
The parameter type for the listAll() method uses a wildcard specification instead of an explicit type
argument. Thus, the method accepts an argument of any LinkedList<> type. Because every object has a
toString() method regardless of the actual type, the argument passed to println() in the body of the
method is always valid. Now you could list the integers in the values object that is of type LinkedList<In-
teger> with the statement:
listAll(values);
You could also list the contents of the sortedWords object of type LinkedList<String> with the state-
ment:
listAll(sortedWords);
You can plug these code fragments, including the definition of the method, of course, into the TryBin-
aryTree class and recompile to see it working.
TRY IT OUT: Using a Wildcard Type Argument
Here's a modified version of the previous example:
public class TryWildCard {
public static void main(String[] args) {
int[] numbers = new int[30];
for(int i = 0 ; i < numbers.length ; ++i) {
numbers[i] = (int)(1000.0*Math.random()); // Random integers
0 to 999
}
// List starting integer values
int count = 0;
System.out.println("Original values are:");
for(int number : numbers) {
System.out.printf("%6d", number);
Search WWH ::




Custom Search