本帖最后由 HM朱蛟 于 2013-3-31 06:11 编辑
小弟请教:就这段代码而言,不考虑其他
同样的处理函数,同样的集合,同样的执行语句。为何换一个位置,产生的效果不同,
一个是放在创建迭代器语句之前,一个是放在其之后.
代码如下,- import java.util.*;
- 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 Run
- {
- public static void main(String[] args)
- {
- ArrayList al = new ArrayList();
-
- al.add(new Person("haha01",1));
- al.add(new Person("haha02",2));
- al.add(new Person("haha01",1));
- al.add(new Person("haha02",2));
- al.add(new Person("haha01",1));
- al.add(new Person("haha05",5));
- al = killEcho(al); //为何放在这里就没有输出?
- Iterator it = al.iterator();//迭代器
- // al = killEcho(al); //放在这里才有输出
- while(it.hasNext())
- {
- Person p = (Person)it.next();
- sop(p.getName()+"...."+p.getAge());
- }
- }
-
- public static ArrayList killEcho(ArrayList list)
- {
- ArrayList al = new ArrayList();
-
- Iterator it = al.iterator();
-
- while(it.hasNext())
- {
- Object obj = it.next();//等于是Object obj = new Person()
-
- if(!al.contains(obj))
- al.add(obj);
- }
- return al;
- }
-
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 |