Java Reference
In-Depth Information
You should copy the BinaryTree.java and LinkedList.java source files from the previous example to
the directory containing TryWildcardArray.java . When you compile this program, you get two warn-
ings from the compiler from the statements that involve explicit casts. Note that to see both warmings,
you must specify the -Xlint:unchecked compiler option. The output will is similar to that from the pre-
vious example. The sorted lists of values is output one value per line because that's how the listAll()
method displays them.
How It Works
You create two arrays using wildcard type specifications:
BinaryTree<?>[] trees = {new BinaryTree<Integer>(), new
BinaryTree<String>()};
LinkedList<?>[] lists = new LinkedList<?>[trees.length];
The length of the trees array is determined by the number of values in the initializing list — two in this
case. You can see that you can happily initialize the array with references to objects of different specific
types as long as they are produced from the generic type BinarayTree<> . The lists array is of type
LinkedList<?>[] and is defined as having the same number of elements as the trees array. You store
the LinkedList<> references returned by the sort() method in these elements eventually.
After creating the array of random integer values, you add them to a binary tree in a loop:
for(int number:numbers) {
((BinaryTree<Integer>)trees[0]).add(number);
}
You can't call the add() method while the reference stored in trees[0] is of type BinaryTree<?> be-
cause the compiler cannot decide on the form of the add() method without having a specific type argu-
ment available. The type argument determines the parameter type for the method. Without that there's no
way to decide how the argument to the method is to be passed. You must cast the reference to a specific
type, BinaryTree<Integer> in this case, to allow the add() method for that type to be called. You get
a warning from the compiler at this point because the compiler cannot verify that this cast is valid. If
it isn't, calling the add() method causes an exception to be thrown at run time so you have to accept
responsibility for it. In this example it works, and the integer values are converted automatically to type
Integer .
You then create an array of String objects as you did in the previous version and add these to the second
binary tree:
for(String word : words) {
((BinaryTree<String>)trees[1]).add(word);
}
Again it is necessary to cast the reference in trees[1] to type BinaryTree<String> , which results in
the second warning from the compiler.
You sort the contents of the binary trees in another loop:
for(int i = 0 ; i < lists.length ; ++i){
lists[i] = trees[i].sort();
}
Search WWH ::




Custom Search