给出两段代码(关于迭代器),在不运行的情况下通过分析,看他们能否通过编译,并解释为什么?
1、- class HashSetDemo
- {
- public static void main(String[] args)
- {
- HashSet hs =new HashSet();
- hs.add(new Person("linlin",22));
- hs.add(new Person("laal",55));
- hs.add(new Person("bbaf",8));
- hs.add(new Person("dfsdf",66));
- Iterator it=hs.iterator();
- while (it.hasNext())
- {
- Person p=(Person)it.next();
- sop(p.getName()+"::::"+p.getAge());
- }
-
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- 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;
- }
- }
复制代码
2、与1大体一致,只修改迭代器那块;
Iterator it=hs.iterator();
while (it.hasNext())
{
//Person p=(Person)it.next();
sop((Person)it.next().getName()+"::::"+(Person)it.next().getAge());
} |
|