Why people recommend use Iterator
if we get ConcurrentModificationException
with forEach ? In my case the best solution for this exception is just use fori instead of foreach.
So I have right ? Please explain to me if I'm wrong
example:
with exception
private void init() {
addToCollection("Dog");
addToCollection("Cat");
showCollection(stringArrayList);
}
private void showCollection(List<String> collection) {
for (String s : collection) {
if (s.equals("Dog")){
collection.remove(s);
}
}
}
private void addToCollection(String value) {
stringArrayList.add(value);
}
}
without:
private void init() {
addToCollection("Dog");
addToCollection("Cat");
showCollection(stringArrayList);
}
private void showCollection(List<String> collection) {
for (int i = 0; i < collection.size(); i++) {
if (collection.get(i).equals("Dog")){
collection.remove(i);
}
}
}
private void addToCollection(String value) {
stringArrayList.add(value);
}