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?
Your question isn’t clear, but I suspect the main point you may be missing is that
ListIterator.addinserts at the current location:And also:
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 toprevious()returns"us"again, and finally a call toset()replaces"us"with"##":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.