简体   繁体   English

使用迭代器时从列表中删除项目而无需访问迭代器 Java

[英]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.我知道 iterator.remove 方法,但这在我的情况下不起作用,因为删除时需要调用其他方法。 (glDeleteTextures) (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.更新:感谢 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.上述方法对我不起作用,因为除了一次调用所有纹理对象之外,我还需要能够对单个纹理对象调用 deleteTextures() 方法。 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以下摘录来自Sun/Oracle's Tutorial on Java Collection

Note that Iterator.remove is the only safe way to modify a collection during iteration;请注意, Iterator.remove是在迭代期间修改集合的唯一安全方法; 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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