Reputation: 347
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();
}
}
Upvotes: 1
Views: 57
Reputation: 7162
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();
}
}
Upvotes: 1