I have the following code but i saw that retrieving values from a Map while iterating over the Map keys with keySet()
is a mistake even with findBugs i get the warning WMI_WRONG_MAP_ITERATOR
for(String elementId : mapElements.keySet()){
element = mapElements.get(elementId);
doSomething(element);
}
so why exactly is this not good and how can i fix it ?
Thanks.
If you're iterating over everything in a map, you might as well do:
for (Map.Entry<String, String> entry : mapElements.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// Use the key and the value
}
Or if you don't really need the key, just iterate over the values:
for (String value : mapElements.values()) {
doSomething(value);
}
EDIT: syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With