remove beim Iterieren einer HashMap

krgewb

Top Contributor
Man sollte niemals in einer for-Schleife (über eine ArrayList) Elemente aus der ArrayList entfernen. Ist folgendes ebenfalls schlecht?
Java:
for (Map.Entry<ClientWSInformation, MyStreamSettings> entry : map.entrySet()) {
    ClientWSInformation clientWSInformation = entry.getKey();
    if (clientWSInformation.getUuidForWs() != null && clientWSInformation.getUuidForWs().equals(uuidForWs)) {
        map.remove(clientWSInformation);
    }
}
 
Ja aus meiner Sicht ist das ebenfalls problematisch: Das map.remove verändert auch das entrySet und über das iterierst Du.

Du hast zwei Möglichkeiten aus meiner Sicht:
a) Iterator verwenden mit der remove Methode des Iterators. So der Iterator dies unterstützt, hast Du so eine gute Lösung (Was hier der Fall sein sollte).
b) Du kannst dir die zu löschenden Elemente merken und dann im Anschluss löschen.

Das findet sich ansonsten auch in der Dokumentation von entrySet():
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
 

Zurück
Oben