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);
}
}
C#'s foreach loop makes it easy to process a collection: there's no index variable, condition, or code to update the loop variable. Instead the loop variable is automatically set to the value of each element. That also means that there's no index variable with foreach .
The index value represents the number of the currently executing iteration. More specifically, the body of the loop (the instructions that are executed during each loop repetition) can be said to be iterated as the loop executes.
Each element in the list can be accessed using iterator with a while loop.
The way to do this is with an explicit Iterator
(no school like the old school!).
Iterator<Properties> it = propertiesList.iterator();
while (it.hasNext()) {
if (it.next().getKey().equals(keyToDelete)) {
it.remove();
}
}
Unlike the remove method on a list, the remove
method 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:
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
No, you need to use the old-school for loop to get an index.
You could of course add it yourself to the for-each loop, but then you would most probably be better off using the old variant instead.
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