import java.util.*;
public class ShowAll {
public static void main(String[] args) {
Queue<Dog> q = new LinkedList<Dog>(); showAll(q);
}
public static void showAll(Queue q){
q.add("love");
System.out.println(q.poll());
q.add(new Integer(42));
while(!q.isEmpty()){
System.out.print(q.remove()+ " ");
}
}}
class Dog{}
public class ShowAll {
public static void main(String[] args) {
Queue<Dog> q = new LinkedList<Dog>(); showAll(q);
}
public static void showAll(Queue q){
q.add("love");
System.out.println(q.poll());
q.add(new Integer(42));
while(!q.isEmpty()){
System.out.print(q.remove()+ " ");
}
}}
class Dog{}
new Integer对象而不会抛出
ClassCastException异常呢??
Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。 此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。
public static void showAll(Queue<Dog> q){
q.add("love");
System.out.println(q.poll());
q.add(new Integer(42));
while(!q.isEmpty()){
System.out.print(q.remove()+ " ");
}
}
我只能这么理解。
其实这里一定要转换成Dog肯定是会出错的。
但
SUN考虑到泛型要与原来的方法兼容。
因为泛型毕竟出现的晚,所以允许这样放入。
能这样解释吗?
请举手。
可以理解为向后兼容,不然以前写的代码就不能在5.0以上的版本上运行了,而且也是告诉你,泛型可用可不用,只是个语法,为了方便而已,能写出更灵活的代码,就像for(... in ...)、自动拆装箱一样,完全可以用之前的语法。