I can't modyfing element of List this way:
for (String s : list)
{
s = "x" + s;
}
After execution this code elements of this list are unchanged How to achieve iteration with modyfing through List in the simplest way.
The list. copy method returns a shallow copy of the object on which the method was called. This is necessary because we aren't allowed to modify a list's contents while iterating over it. However, we can iterate over a copy of the list and modify the contents of the original list.
Iterating using Iterator/ListIterator allows to add/remove element and these modification (add/remove) is reflected in the original List.
ArrayList provides the remove() methods, like remove (int index) and remove (Object element), you cannot use them to remove items while iterating over ArrayList in Java because they will throw ConcurrentModificationException if called during iteration.
The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .
Since String
objects are immutable, you cannot change the values you're iterating over. Furthermore, you cannot modify the list you're iterating over in such a loop. The only way to do this is to iterate over the list indexes with a standard loop or to use the ListIterator
interface:
for (int i = 0; i < list.size(); i++)
{
list.set(i, "x" + list.get(i));
}
for (ListIterator i = list.listIterator(); i.hasNext(); )
{
i.set("x" + i.next());
}
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