高手进来指点一下有关Iterator的使用问题 要求:对程序做出修改,用LinkedList代替ArrayList,并使用Iterator来循环遍历事件集。原程序比较长下面是关键的部分程序 //: mypackage/Event.java package mypackage; public abstract class Event { private long eventTime; protected final long delayTime; public Event(long delayTime) { this.delayTime=delayTime; start(); } public void start() { eventTime=System.nanoTime()+delayTime; } public boolean ready() { return System.nanoTime()>=eventTime; } public abstract void action(); }
//: mypackage/Controller.java package mypackage; import java.util.*; public class Controller { private List<Event> eventList=new ArrayList<Event>(); public void addEvent(Event c) { eventList.add(c); } public void run() { while(eventList.size()>0) for(Event e:new ArrayList<Event>(eventList)) if(e.ready()) { e.action(); eventList.remove(e); } } }
上面的程序是正确的,运行正常。下面是我修改以后的程序,只改动Controller类里的eventList类型跟run()方法的遍历实现,可是修改后的程序出错了,想了很久想不出原因希望高手能指点一二。。修改后Controller类如下: public class Controller { private LinkedList<Event> eventList=new LinkedList<Event>(); Iterator<Event> it=eventList.iterator(); public void addEvent(Event c) { eventList.add(c); } public void run() { Event e; while(eventList.size()>0) while(it.hasNext()) { e=it.next(); if(e.ready()) { e.action(); it.remove(); } } } } //Iterator<Event> it=eventList.iterator();到底要放到run()方法里还是方法外我有点 //模糊不过放到run()里一样出错,希望高手能指出问题并给个简明的修改方案,小弟不胜感激!