关于ArrayList的问题:

yunors 2012-09-01 07:45:04

import java.util.*;
class SoccerMember
{

private String name;
private int age;
SoccerMember(int age,String name)
{
this.name=name;
this.age=age;
}
String getName()
{
return name;
}
int getAge()
{
return age;
}
}

class CollectionDemo
{
public static void main(String[] args)
{

ArrayList al = new ArrayList();

al.add(new SoccerMember(25,"梅西"));
al.add( new SoccerMember(40,"齐达内"));
al.add( new SoccerMember(27,"C罗"));
for (Iterator it = al.iterator();it.hasNext(); )
{

System.out.println(it.next());
//System.out.println(it.next().getAge());//无法编译通过
}
/*
for (int i=0;i<al.size();i++ )
{
System.out.println(al.get(i));
}
*/

}
}


以下是问题:
1,以上将对象存入到al中,请问,如何取出每个元素中的getAge()方法?
2,注释掉的for循环和使用Iterator迭代器的for循环有相同的作用,请问,差别是什么?
...全文
169 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
jijihahalala 2012-09-01
  • 打赏
  • 举报
回复
泛型加foreach好用,我喜欢这么用
ncist_jianeng 2012-09-01
  • 打赏
  • 举报
回复
使用泛型就可以了
ArrayList<SoccerMember> al = new ArrayList<SoccerMember>();
yunors 2012-09-01
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

差别是用数组的思维还是集合的思维....
[/Quote]
。。。只有这个差别?
yunors 2012-09-01
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

要把it.next()强制转换成SoccerMember那个for循环也可以遍历,取出来强转
[/Quote]
多谢!存进去的是Object类型,这下明白了。
不过这个代码:
System.out.println(((SoccerMember)(it.next())).getAge());
看起来一点都不性感,好繁琐。。。
Woodpecker 2012-09-01
  • 打赏
  • 举报
回复
差别是用数组的思维还是集合的思维....
x123_ 2012-09-01
  • 打赏
  • 举报
回复
System.out.println(SoccerMember.it.next());
System.out.println(SockerMember.it.next().getAge());
jijihahalala 2012-09-01
  • 打赏
  • 举报
回复
要把it.next()强制转换成SoccerMember那个for循环也可以遍历,取出来强转
蝴蝶又来了 2012-09-01
  • 打赏
  • 举报
回复
ArrayList就像一个麻袋,<SoccerMember>就相当于麻袋上的标签

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧