-3

Im trying to add to a ListIterator while iterating over it but when checking if it worked hasNext() always returns false.

As javadoc states that a ListIterator is "An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list." however when Im trying to add I'm neither getting an Error message nor is the ListIterator getting a new Element.

public void foo() {
    List<String> bar = new ArrayList<String>();
    bar.add("foobar");
    ListIterator<String> quux = bar.listIterator();
    while(quux.hasNext()) {
        if(quux.next().equals("foobar")) {
            quux.add("baz");
        }
    }
}

At the end of this funtion I expect the ListIterator to contain the new String "baz". However when I call the hasNext() method it returns false. The program even got past the if-Statement it just turns out, that the add-method doesnt do what its supposed to do.

2 Answers2

0

Your code works (after fixed the missed () after new ArrayList<String> and replaced == with the correct method to compare strings, equals:

import java.util.*;

public class test
{
    public static void main(String[] args) {
        List<String> bar = new ArrayList<String>();
        bar.add("foobar");
        ListIterator<String> quux = bar.listIterator();
        while(quux.hasNext()) {
            if(quux.next().equals("foobar")) {
                quux.add("baz");
            }
        }
        System.out.println(bar);
    }
}

returns:

[foobar, baz]

As you can see, baz were inserted.

user2342558
  • 5,567
  • 5
  • 33
  • 54
  • Thanks for the fast answer, I added the missing () in the code for this site, but the objects Im comparing are not really Strings, I just used Strings to simplify the problem as I am using a self defined class and in fact Im getting inside the if-Branch where I call the add function just to see that nothing changes in the Iterator. – Lucien Nestler Oct 16 '19 at 09:10
  • @LucienNestler You're welcome. Please flag my answer as accepted and upvote it. If you'll open a new question about this with the reral types I'll answer it – user2342558 Oct 28 '19 at 13:01
0

It seems that you expect to be able to fetch the added element with next():

nor is the ListIterator getting a new Element

[...]

At the end of this funtion I expect the ListIterator to contain the new String "baz". However when I call the hasNext() method it returns false

However, the JavaDoc for ListIterator.add() explicitly states that this is not the case:

The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected


If you want to include the element in the iteration you can rewind the list iterator by one position:

    if(quux.next().equals("foobar")) {
        quux.add("baz");
        quux.previous();
    }
Community
  • 1
  • 1
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34