请教一下大家这段程序为何编译失败呢,我记得之前毕老师讲过的一个例子好像这样是可以打印的可是现在为何不可以呢?好像和和转型有关,请大家帮我详细解释一下谢了
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class ArrayListTest2
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(new Person("lisi01",30));
al.add(new Person("lisi02",32));
al.add(new Person("lisi03",33));
al.add(new Person("lisi04",35));
Iterator it=al.iterator();
while(it.hasNext())
{
sop(it.next().getName()+"...."+it.next().getAge());
}
}
}
结果是把
while(it.hasNext())
{
sop(it.next().getName()+"...."+it.next().getAge());
}
改成
while(it.hasNext())
{
Person p=(Person)it.next();
sop(p.getName()+"...."+p.getAge());
}
为何是这样的呢?没理解
|