简体   繁体   中英

Remove item from list while using iterator without acess to iterator Java

I want to remove items from an iterator as I go through it, but also be able to remove items from the list using another method. Here is the code I'm currently using that throws an error. I'm aware of the iterator.remove method but that won't work in my case because of the additional method needed to be called when removing. (glDeleteTextures)

public void cleanUp() {
    glDeleteTextures(textureID);
    textures.remove(this);
}

public static void cleanUpAllTextures() {
    Iterator<Texture> i = textures.iterator();
    while (i.hasNext()) {
        i.next().cleanUp();
    }

}

Update: Thanks for the help leeyuiwah. The above method won't work for me because I need to be able to call the deleteTextures() method on individual texture objects instead in addition to all of them at once. The method I've decided to go with is this:

public void cleanUp() {
        glDeleteTextures(textureID);
        textures.remove(this);
    }

    public static void cleanUpAllTextures() {
        while(textures.size() > 0) {
            textures.get(0).cleanUp();
        }
    }

I think you may want to reconsider your design. What you want to do is not recommended. The follow excerpt come from Sun/Oracle's Tutorial on Java Collection

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Updated

An example of design change is the following:

public void deleteTextures() {
    glDeleteTextures(textureID);
}

public static void cleanUpAllTextures() {
    Iterator<Texture> i = textures.iterator();
    while (i.hasNext()) {
        i.next().deleteTextures();
        i.remove();
    }
}

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