我的ArrayList迭代器或List的get()函数(带有几个索引)总是返回列表的最后一个元素。我是Java的新手,无法理解为什么没有像C ++那样的迭代器的begin()和end()。我怎样才能跳到第一个元素? 如果我通过带有hasNext()和next()以及Log()的列表的迭代器while()到控制台,如果列表的大小为20,则有20倍的相同对象。
对象:
public class JokeObject implements Serializable {
private static final long serialVersionUID = -1703441755022251852L;
public int num;
public int jokeid;
public String joke;
public int votes;
}
对象持有者类:
public class JokeHolder {
private ArrayList <JokeObject> jokeList;
private Iterator<JokeObject> jokeIt;
private JokeObject lastJokeObj;
public JokeHolder() {
jokeList = new ArrayList<JokeObject>();
jokeIt = jokeList.iterator();
lastJokeObj = null;
}
public void AddJoke(JokeObject obj) {
this.jokeList.add(obj);
}
public JokeObject GetNextJoke() {
if (jokeIt.hasNext()) {
lastJokeObj = jokeIt.next();
return lastJokeObj;
}
return null;
}
public int GetHolderSize() {
return (jokeList.size());
}
public void SetList(ArrayList<JokeObject> aList) {
jokeList.clear();
jokeList.addAll(aList);
this.jokeIt = this.jokeList.iterator();
}
public void SetLastObj(JokeObject obj) {
this.lastJokeObj = obj;
}
public ArrayList<JokeObject> GetList() {
return jokeList;
}
public JokeObject GetLastObject() {
return lastJokeObj;
}
}
在活动A:
jokes.AddJoke(obj);
在活动B中:
obj = myJokes.GetNextJoke();
答案 0 :(得分:0)
当您将项目添加到列表时,我认为迭代器不会“刷新”。也许这会更好。存储你的笑话的索引并得到这样的笑话:
public JokeObject GetNextJoke() {
if (if index < jokeList.size()) {
lastJokeObj = jokeList.get(i);
index++;
return lastJokeObj;
}
return null;
}