Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator for replacing list members in Java?

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.

like image 313
Jason S Avatar asked May 12 '09 16:05

Jason S


People also ask

Can we modify list with Iterator in Java?

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.

How do you replace a character in a list in Java?

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.

How do you modify an ArrayList while iterating?

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.

Can we update list while iterating?

Because you iterate over a copy of the list, you can modify the original list without damaging the iterator.


1 Answers

ListIterator.set as returned by List.listIterator() or List.listIterator(int)

(set wouldn't make any sense for, say, a Set iterator.)

like image 144
Tom Hawtin - tackline Avatar answered Sep 23 '22 10:09

Tom Hawtin - tackline