Search code examples
javaarraylistsublistlistiterator

Adding an element in a sublist through a list iterator


I have an arraylist that contains elements-

0, 100, 200, 300, 400, 500, 600, 700...

After getting a sublist out of the main list, I am adding an element if the element returned by next() is 400

public static void add(List<String> list){
    List<String> subList = list.subList(2, 7);// 200, 300, 400, 500, 600
    ListIterator<String> listIterator = subList.listIterator();

    while(listIterator.hasNext()) {

        String value = listIterator.next();

        if(value.equals("400")) {
            listIterator.add("399");
        }

    }
    System.out.println(subList);
}

The sublist now becomes -

[200, 300, 400, 399, 500, 600]

As seen visible, the element 399 is after 400.

The doc says

Inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next()....

Please clarify.


Solution

  • Inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next()

    It means the element will be inserted immediately before the element that would be returned by the next call to next() (i.e. the call to next() that takes place after the call to listIterator.add("399"), not before it), which is 500. Therefore the new element is added before 500.