0

我想将循环中的元素添加到列表中,这样循环体也将为它们执行。我知道这种技术很常见,以防止ConcurrentModificationException

List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
    Element element = it.next();
    if(...) {  
         //irrelevant stuff..
        if(element.cFlag){
            // mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            element.cFlag = false;
       }           
   }
}
mElements.addAll(thingsToBeAdd );

不幸的是,它不会为新元素执行循环。

编辑:

List<Element> thingsToBeAdd = new ArrayList<Element>();
for(Iterator<Element> it = mElements.iterator(); it.hasNext();) {
    Element element = it.next();
    if(...) {  
        //irrelevant stuff..
        if(element.cFlag){
            // mElements.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            thingsToBeAdd.add(new Element("crack",getResources(), (int)touchX,(int)touchY));
            element.cFlag = false;
       }           
   }
   mElements.addAll(thingsToBeAdd );
}

这将导致ConcurrentModificationException.

4

3 回答 3

0

你不是在mElements循环完成后添加元素吗

mElements.addAll(thingsToBeAdd );
于 2012-08-23T08:15:34.853 回答
0

你试过CopyOnWriteArrayList吗?

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

于 2012-08-23T08:28:37.093 回答
0

我使用递归实现了我的目标:

private List<Element> executeForEachElement(List<Element> oldList)
    List<Element> newElements = new LinkedList<Element>();
    for (Element elem : oldList {
            newElements.addAll(generateNewElements(elem));
    }
    if (!newElements.isEmpty()) {
        oldList.addAll(executeForEachElement(newElements));
    }

    return oldList;
}
于 2012-08-23T09:00:30.040 回答