[英]Remove item from list while using iterator without acess to iterator Java
我想在遍歷迭代器時從迭代器中刪除項目,但也可以使用另一種方法從列表中刪除項目。 這是我目前正在使用的代碼,它會引發錯誤。 我知道 iterator.remove 方法,但這在我的情況下不起作用,因為刪除時需要調用其他方法。 (glDeleteTextures)
public void cleanUp() {
glDeleteTextures(textureID);
textures.remove(this);
}
public static void cleanUpAllTextures() {
Iterator<Texture> i = textures.iterator();
while (i.hasNext()) {
i.next().cleanUp();
}
}
更新:感謝 leeyuiwah 的幫助。 上述方法對我不起作用,因為除了一次調用所有紋理對象之外,我還需要能夠對單個紋理對象調用 deleteTextures() 方法。 我決定采用的方法是:
public void cleanUp() {
glDeleteTextures(textureID);
textures.remove(this);
}
public static void cleanUpAllTextures() {
while(textures.size() > 0) {
textures.get(0).cleanUp();
}
}
我認為您可能需要重新考慮您的設計。 不推薦你想做的事情。 以下摘錄來自Sun/Oracle's Tutorial on Java Collection
請注意,
Iterator.remove
是在迭代期間修改集合的唯一安全方法; 如果在迭代過程中以任何其他方式修改了基礎集合,則行為是未指定的。
更新
設計更改的示例如下:
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.