Java Reference
In-Depth Information
// Sort the words
LinkedList<String> sortedWords = cache.sort();
// List the sorted words
System.out.println("\nSorted word sequence:");
count = 0;
for(String word : sortedWords) {
System.out.printf("%-15s", word);
if(++count%5 == 0) {
System.out.println();
}
}
}
}
Directory "TryBinaryTree"
The output should be along the lines of the following:
Original values are:
110 136 572 589 605 832
565 765 514 616 347 724
152 527 124 324 42 508
621 653 480 236 1 793
324 31 127 170 724 546
Sorted values are:
1 31 42 110 124 127
136 152 170 236 324 324
347 480 508 514 527 546
565 572 589 605 616 621
653 724 724 765 793 832
Original word sequence:
vacillate procrastinate arboreal syzygy xenocracy
zygote mephitic soporific grisly gristly
Sorted word sequence:
arboreal grisly gristly mephitic
procrastinate
soporific syzygy vacillate xenocracy zygote
How It Works
You have defined
BinaryTree<T>
with a type parameter that is constrained to implement the parameter-
ized interface type
Comparable<T>
. Thus, any type argument that you use with the
BinaryTree<T>
type
must implement the
Comparable<T>
interface. If it doesn't, the code doesn't compile. This ensures that
all objects added to a
BinaryTree<T>
object have the
compareTo()
method available.
The definition for
BinaryTree<T>
also demonstrates that a generic type can include references to other
generic types —
LinkedList<T>
in the
sort()
method for example and the second parameter to the
treeSort()
method. The type of the
LinkedList<T>
return value is determined by the type argument