您的位置:首页 > 编程语言 > Java开发

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

2013-11-12 23:19 603 查看
控制台程序

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

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

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

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);
if(++count%6 == 0) {
System.out.println();
}
}

// Create the tree and add the integers to it
BinaryTree<Integer> tree = new BinaryTree<>();
for(int number:numbers) {
tree.add(number);
}

// Get sorted values
LinkedList<Integer> values = tree.sort();
System.out.println("\nSorted values are:");
listAll(values);

// Create an array of words to be sorted
String[] words = {"vacillate", "procrastinate", "arboreal",
"syzygy", "xenocracy", "zygote",
"mephitic", "soporific", "grisly", "gristly" };

// List the words
System.out.println("\nOriginal word sequence:");
for(String word : words) {
System.out.printf("%-15s", word);
if(++count%5 == 0) {
System.out.println();
}
}

// Create the tree and insert the words
BinaryTree<String> cache = new BinaryTree<>();
for(String word : words) {
cache.add(word);
}

// Sort the words
LinkedList<String> sortedWords = cache.sort();

// List the sorted words
System.out.println("\nSorted word sequence:");
listAll(sortedWords);
}

// List the elements in any linked list
public static void listAll(LinkedList<?> list) {
for(Object obj : list) {
System.out.println(obj);
}
}
}


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

当然,依赖继承的toString()方法来在输出中表示对象在很多情况下并不理想。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐