黑马程序员技术交流社区

标题: 泛型通配符 [打印本页]

作者: 卢祥洲    时间: 2013-6-15 16:27
标题: 泛型通配符
本帖最后由 卢祥洲 于 2013-6-15 16:52 编辑
  1. import java.util.*;
  2. class Person{
  3.         private String name;
  4.         Person(String name){
  5.                 this.name= name;        
  6.         }        
  7.         public String getName(){
  8.                 return name;        
  9.         }
  10. }
  11. public class GenericDemo06{
  12.                 public static void main(String[] args){
  13.                         ArrayList<Person> al1 = new ArrayList<Person>();
  14.                         al1.add(new Person("def"));
  15.                         al1.add(new Person("sfde"));
  16.           al1.add(new Person("dfdf"));
  17.                         printColl(al1);
  18.                 }
  19.                 public static void printColl(ArrayList<?> a){//这里通配符ArrayList<?>不行
  20.                         Iterator<?> it = a.iterator();//这里通配符ArrayList<?>不行
  21.                         while(it.hasNext()){
  22.                                         System.out.println(it.next().getName());
  23.                         }
  24.                 }
  25. }
复制代码

使用上面通配符编译报错,把上面通配符改成Person就可以了,这是为啥啊?通配符接受不是可以的吗?ArrayList<?> a = ArrayList<Person>();这样不行,为啥?
作者: 苑永志    时间: 2013-6-15 16:33
楼主我刚才调试了一边,通配符?的使用是没有问题的。只有System.out.println(it.next().getName());这里需要强制转型一下System.out.println(((Person)it.next()).getName());
楼主你再调试看看,理论上是没有错误的呀。
作者: 卢祥洲    时间: 2013-6-15 16:51
苑永志 发表于 2013-6-15 16:33
楼主我刚才调试了一边,通配符?的使用是没有问题的。只有System.out.println(it.next().getName());这里需 ...

谢啦
  1. import java.util.*;
  2. class Person{
  3.         private String name;
  4.         Person(String name){
  5.                 this.name= name;       
  6.         }       
  7.         public String getName(){
  8.                 return name;       
  9.         }
  10. }
  11. public class GenericDemo06{
  12.                 public static void main(String[] args){
  13.                         ArrayList<Person> al1 = new ArrayList<Person>();
  14.                         al1.add(new Person("def"));
  15.                         al1.add(new Person("sfde"));
  16.                         al1.add(new Person("dfdf"));
  17.                         printColl(al1);
  18.                 }
  19.                 public static void printColl(ArrayList<?> a){
  20.                         a.add(new Person("aaaaa"));

  21.                         Iterator<?> it = a.iterator();
  22.                         while(it.hasNext()){
  23.                                         System.out.println(((Person)it.next()).getName());
  24.                                         //通配符?是所有泛型的父类,但是迭代器返回出来时不知道是什么类型,所有要加Person进行强制转换
  25.                                         //注意括号
  26.                         }
  27.                 }
  28. }
复制代码

作者: 苑永志    时间: 2013-6-15 16:54
卢祥洲 发表于 2013-6-15 16:51
谢啦

甭客气,互相交流




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2