Pregunta

I have the following code:

    ArrayList<String> words;
    words = new ArrayList<String>();
    words.add("is");
    words.add("us");
    ListIterator<String> it;
    it = words.listIterator();
    it.add("##");
    System.out.println(words);
    it.next();
    it.next();
    it.previous();
    it.set("##");
    System.out.println(words);

I would expect that the output would be ## us ##, but when I run the program it returns ## is ##. I expect that this has to do with the ListIterator adding an item to the ArrayList instead of the ArrayList adding an item to its self.

Why does the program behave in this way?

¿Fue útil?

Solución

Your question isn't clear, but I suspect the main point you may be missing is that ListIterator.add inserts at the current location:

The element is inserted immediately before the next element that would be returned by next(), if any, and after the next element that would be returned by previous(), if any.

And also:

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

So after your initial call to it.add("##") the list contains "##", "is" "us". You're then moving next twice - the first moves the cursor to just after "is" (which is returned). The second moves the cursor to just after "us" (which is returned). Then the call to previous() returns "us" again, and finally a call to set() replaces "us" with "##":

Replaces the last element returned by next() or previous() with the specified element (optional operation).

It all looks like it's obeying the documentation perfectly. Unfortunately it's not clear which of these steps is confusing you, as you've conflated so many in one question.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top