Given the code below, is it possible to remove the index of p from the properties list using this style of for loop in Java?
List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";
for(Properties p : propertiesList) {
if(p.getKey().equals(keyToDelete)) {
propertiesList.remove(index) //How to remove the element at index 'p'
}
}
This is how i would accomplish this with the other for loop
List<Properties> propertiesList = new ArrayList<Properties>();
String keyToDelete = "blah";
for(int i = 0; i < propertiesList.size(); i++) {
if(p.getKey().equals(keyToDelete)) {
propertiesList.remove(i);
}
}
The way to do this is with an explicit
Iterator(no school like the old school!).Unlike the remove method on a list, the
removemethod on the iterator doesn’t cause a concurrent modification. It’s the only safe way to remove an element from a collection you’re iterating over. As the javadoc for that method says: