Course contentsShow
← Java
Lesson 1286 of 2,87029. Iterators and IterableFree lesson

Modifying Elements with set

Using set(E element) to replace the last element returned by next() or previous() during iteration.

Modifying Elements with set

You'll learn how to replace elements in a list during iteration using the ListIterator's set method.

When you're traversing a list with a ListIterator, you're not just limited to reading or removing elements—you can also replace the element you just visited. The set(E element) method lets you swap out the last element returned by next() or previous() with a new value.

How set Works

Think of set like editing a book as you read it. When you finish reading a paragraph (by calling next()), you can immediately rewrite that same paragraph before moving on. The set method targets whatever element was most recently handed to you by the iterator.

Here's the key behavior:

  • You must call next() or previous() first to establish which element you're modifying
  • Then you call set(newValue) to replace that element
  • If you try to call set before calling next()/previous(), or after calling remove() or add(), you'll get an IllegalStateException

Example Pattern

List<String> words = new ArrayList<>(Arrays.asList("cat", "dog", "bird"));
ListIterator<String> iter = words.listIterator();

while (iter.hasNext()) {
    String word = iter.next();
    if (word.equals("dog")) {
        iter.set("puppy"); // Replaces "dog" with "puppy"
    }
}
// words is now ["cat", "puppy", "bird"]

When set Is Useful

Use set when you need to transform list elements in-place during iteration—for example, capitalizing strings, updating object properties, or applying filters that modify rather than remove.

Key Takeaway: ListIterator.set(E element) replaces the element most recently returned by next() or previous(), allowing safe in-place modification during iteration.