简体   繁体   中英

Removing element from innermost nested Iterator in java causes NoSuchElementException

I keep crashing and getting java.util.NoSuchElementException at the if statement. I was under the impression that while(Iterator.hasNext()) ensured that a Iterator.next() call wouldn't cause a buffer overrun.

What is the correct algorithm to loop through two nested iterators, and remove elements from one of the iterators when a match is found, without throwing such an exception (which I think is caused by overrunning the array bounds)?

enter code here {

    Iterator<Integer> d = entitiesDeleteQueue.iterator();
    Iterator<Entity> e = entities.iterator();


    while (d.hasNext()) {

        while (e.hasNext()) {

            if (d.next() == e.next().getEntityId())

                e.remove();
        }   
    }
}

You need to combine your two hasNext conditions to avoid overrun of either iterator:

while (d.hasNext() && e.hasNext()) {
    if (d.next() == e.next.getEntityId())
        e.remove();
}

The problem is that nesting iterators isn't as straightforward as nesting for loops. It requires assigning Iterator.next() to an object reference, that way the iterator doesn't advance every time you need to access the element. The referencing must be done in each layer of the nest, and the second iterator must be created inside the outer loop. Then you can perform operations without overrunning the ArrayList by too many next() calls.

List<Entity> entities = new ArrayList<Entity>();
List<Entity> entityDeleteQueue = new ArrayList<Entity>(); 

Iterator<Entity> e = entities.iterator();

    while (e.hasNext()) {

        Entity liveEntity = e.next();
        Iterator<Entity> d = entityDeleteQueue.iterator();

        while (d.hasNext()) {

            Entity deadEntity = d.next();

            if( deadEntity.getEntityId() == liveEntity.getEntityId()){

                System.out.println("Dead entity: " + deadEntity.getEntityId());

                System.out.println("Removing entity " + liveEntity.getEntityId());

                e.remove();
            }
        }
    }

    for (Entity survivor: entities){

        System.out.println("Remaining entity: " + survivor.getEntityId());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM