Java基础之泛型——使用通配符类型参数(TryWildCard)

控制台程序

使用通配符类型参数可以设定方法的参数类型,其中的代码对于泛型类的实际类型参数不能有任何依赖。如果将方法的参数类型设定为Binary<?>,那么方法可以接受BinaryTree<String>、BinaryTree<Double>或任意BinaryTree<>类型的参数。

LinkedList<T>和BinaryTree<T>和上一例子一样。

下面是上一个例子的修改版本:

 1 public class TryWildCard {
 2   public static void main(String[] args) {
 3     int[] numbers = new int[30];
 4     for(int i = 0 ; i < numbers.length ; ++i) {
 5       numbers[i] = (int)(1000.0*Math.random());                        // Random integers 0 to 999
 6     }
 7     // List starting integer values
 8     int count = 0;
 9     System.out.println("Original values are:");
10     for(int number : numbers) {
11       System.out.printf("%6d", number);
12       if(++count%6 == 0) {
13         System.out.println();
14       }
15     }
16 
17     // Create the tree and add the integers to it
18     BinaryTree<Integer> tree = new BinaryTree<>();
19     for(int number:numbers) {
20       tree.add(number);
21     }
22 
23     // Get sorted values
24     LinkedList<Integer> values = tree.sort();
25     System.out.println("
Sorted values are:");
26     listAll(values);
27 
28     // Create an array of words to be sorted
29     String[] words = {"vacillate", "procrastinate", "arboreal",
30                       "syzygy", "xenocracy", "zygote",
31                       "mephitic", "soporific", "grisly", "gristly" };
32 
33     // List the words
34     System.out.println("
Original word sequence:");
35     for(String word : words) {
36       System.out.printf("%-15s", word);
37       if(++count%5 == 0) {
38         System.out.println();
39       }
40     }
41 
42     // Create the tree and insert the words
43     BinaryTree<String> cache = new BinaryTree<>();
44     for(String word : words) {
45       cache.add(word);
46     }
47 
48     // Sort the words
49     LinkedList<String> sortedWords = cache.sort();
50 
51     // List the sorted words
52     System.out.println("
Sorted word sequence:");
53     listAll(sortedWords);
54   }
55 
56   // List the elements in any linked list
57   public static void listAll(LinkedList<?> list) {
58     for(Object obj : list) {
59       System.out.println(obj);
60     }
61   }
62 }

listAll()方法的参数类型使用通配符规范而不是显式的类型参数。因此,该方法接受任意LinkedList<>类型的参数。因为每个对象不论实际类型是什么都有toString()方法,所以在方法体中传递给println()的参数总是有效。

当然,依赖继承的toString()方法来在输出中表示对象在很多情况下并不理想。