【发布时间】:2016-03-28 15:32:13
【问题描述】:
我在获取使用迭代器背后的逻辑时遇到问题。我需要能够从循环内的 ArrayList 中删除元素,所以我想我会使用 Iterator 对象。但是,我不确定如何将原始代码转换为迭代器。
原始循环:
ArrayList<Entity> actorsOnLocation = loc.getActors();
int size = actorsOnLocation.size();
if (size > 1) {
for(Entity actor: actorsOnLocation) {
// Loop through remaining items (with index greater than current)
for(int nextEnt=index+1; nextEnt < size-1; nextEnt++) {
Entity opponent = actorsOnLocation.get(nextEnt);
// Here it's possible that actor or opponent "dies" and
// should be removed from the list that's being looped
}
}
}
我知道我必须使用 while 循环,它适用于第一个循环。但是如何将第二个循环的条件转换为与迭代器一起使用的条件? This post 表示您可以在任何时候获取迭代器,但在 the documentation 我找不到诸如 .get 方法之类的任何东西。
ArrayList<Entity> actorsOnLocation = loc.getActors();
int size = actorsOnLocation.size();
Iterator actorsIterator = actorsOnLocation.iterator();
// How to get size of an iterator?
if (size > 1) {
while(actorsIterator.hasNext()) {
Entity actor = (Entity) actorsIterator.next();
// How to get current index?
int index = actorsIterator.indexOf(actor);
// How to convert these conditions to Iterator?
for(int nextEnt=index+1; nextEnt < size-1; nextEnt++) {
Entity opponent = actorsOnLocation.get(nextEnt);
// Here it's possible that actor or opponent "dies" and
// should be removed from the list that's being looped
// If the actor dies, the outer loop should skip to the next element
}
}
}
最后一个问题:如果您在迭代器中访问一个元素,该元素不是原始元素的副本,对吗?换句话说,我可以为该元素设置属性,然后通过访问原始 Collection 来访问这些更改的属性?
作为Eran pointed out,这可能不像看起来那么简单,因为两个循环遍历同一个列表并可能相互干扰。那么问题来了,我该如何解决这个问题呢?
【问题讨论】:
标签: java loops arraylist iterator