Hmmm... the Java Iterator<T>
has a remove()
method but not a replace(T replacement)
method.
Is there an efficient way to replace selected items in a List? I can use a for-loop to call get(i) and set(i) which is fine for ArrayList, but would suck for a linked list.
The Best Answer is. At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.
To replace an element in Java ArrayList, set() method of java. util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.
Replace element in arraylist while iterating Do not use iterator if you plan to modify the arraylist during iteration. Use standard for loop, and keep track of index position to check the current element. Then use this index to set the new element. Java program to search and replace an element in an ArrayList.
Because you iterate over a copy of the list, you can modify the original list without damaging the iterator.
ListIterator.set
as returned by List.listIterator()
or List.listIterator(int)
(set
wouldn't make any sense for, say, a Set
iterator.)
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