Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration of List<String> with modyfing String

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.

like image 534
j2j Avatar asked Jan 31 '11 13:01

j2j


People also ask

Can we modify list while iterating?

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.

What happens if you modify the value of an element in a list while iterating using iterators?

Iterating using Iterator/ListIterator allows to add/remove element and these modification (add/remove) is reflected in the original List.

Can we modify ArrayList while iterating?

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.

Can you use enhanced for loop on list?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .


1 Answers

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());
}
like image 73
Gabe Avatar answered Oct 30 '22 04:10

Gabe