2017-01-23 65 views
1

我想在迭代器中刪除項目,但也能夠使用其他方法從列表中刪除項目。這是我目前使用的代碼會引發錯誤。我知道iterator.remove方法,但這不適用於我的情況,因爲刪除時需要調用其他方法。 (glDeleteTextures)從列表中刪除項目,同時使用迭代器而無需訪問迭代器Java

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(); 
     } 
    } 
+0

使用列表的副本,也許? – njzk2

+0

您必須決定克隆列表並使用'List#remove'(在處理圖形時可能不太好),或者對'textures'使用itsellf並使用'Iterator#remove' –

回答

1

我想你可能想重新考慮你的設計。不建議你想要做什麼。後續摘錄來自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(); 
    } 
}