简体   繁体   中英

Changing list while iterating over it and iterating over new elements

i was wondering if this is possible, and if it is, how can i do it? Basically what i saw, and think is problem is that cursor of iterator is moving when I am using add function(I dont understand iteration perfectly so I dont know if this is problem).The problem happens when i remove one element and then add two more(that is specific case where i found a problem).

My code is something like this:

List<String> list =new ArrayList<>();
for (ListIterator<String> iterator = list.listIterator(); iterator.hasNext();)
      //here i am adding and removing elements

ListIterator According to JLS

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. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions, as illustrated by the carets (^) below:

在此处输入图片说明

You can use the add(), remove() method to make the modification in iterator and same will be reflected in the list reference.


Remove as per JLS

Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only be made once per call to next or previous. It can be made only if add(E) has not been called after the last call to next or previous.

So if you use remove twice without calling next() or previous() it will throw java.lang.IllegalStateException
I modified your code to test add() and remove()

public static void main(String[] args) {

    List<String> list =new ArrayList<>();
    list.add("55");
    list.add("155");
    list.add("255");
    for (ListIterator<String> iterator = list.listIterator(); iterator.hasNext();){

        System.out.println(list.size());
        iterator.add("88");
        System.out.println(list.size());
        iterator.next();
        System.out.println(list.size());
        iterator.remove();
        System.out.println("first remove done");
        iterator.remove();  // will throw exception if previous or next is not called
    }

    System.out.println(list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM