黑马程序员技术交流社区

标题: 泛型问题,跪求解答 [打印本页]

作者: 妖妖    时间: 2015-3-30 20:41
标题: 泛型问题,跪求解答
class GenericDemo8
{
        public static void main(String[] args)
        {
                ArrayList<Person> al=new ArrayList<Person>();
                al.add(new Person("zhangsan1",3));
                al.add(new Person("zhangsan2",3));
                al.add(new Person("zhangsan3",3));
                printColl(al);
        }
        public static void printColl(ArrayList <? extends Person> al)
        {
                Iterator<? extends Person> it=al.iterator();
                while (it.hasNext())
                {
                        //System.out.println(it.next().getName());
                        System.out.println(it.next().getAge());
                }
        }
}
注解Person类与Student类已经写好
问题是,我想同时输出name和age要怎么办?跪求答案啊!!!
作者: 菜鸟小A    时间: 2015-3-30 21:12
Person p = it.next();
String name = p.getName();
int age = p.getAge();
作者: 快乐ABC    时间: 2015-3-31 00:00
可以在循环中   
Person  p = it.next();//当集合中是Person时,直接取出。当集合中是Student时,就是向上转型。
String name = p.getName();
int age = p.getAge();




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