I am iterating over a ArrayList using a ListIterator. I am using the ListIterator to add and remove Elements while iterating over the ArrayList. The Problem is that every time i am adding an element the new element will be iterated too. But i want to iterate only over the inital Elements in the list and not over the new added Elements.

How can this be done?

Thank you all.

有帮助吗?

解决方案

It depends what you want the resulting list to look like.

If you're happy for the new elements to exist in amongst the elements that were there originally, then you can take ZouZou's example and use the ListIterator add() and remove() methods.

final List<Integer> list = new ArrayList<Integer>(Arrays.asList(2,3,4,5,6));
final ListIterator<Integer> ite = list.listIterator();
while( ite.hasNext() ) {
    if( ite.next() %2 == 0 ) {
        ite.add( 7 );
    }
    else {
        ite.remove(); //removes the last value returned by next()
    }
}

Output:

list = [2, 7, 4, 7, 6, 7]

However, if you want the new elements to all be after the original elements, then a second collection is your best bet.

final List<Integer> list = new ArrayList<Integer>(Arrays.asList(2,3,4,5,6));
final List<Integer> newList = new ArrayList<Integer>(list);
final ListIterator<Integer> ite = list.listIterator();
while( ite.hasNext() ) {
    final Integer next = ite.next();
    if( next % 2 == 0 ) {
        newList.add( 7 );
    }
    else {
        newList.remove(next);
    }
}

Output:

newList = [2, 4, 6, 7, 7, 7]

Personally, I've always been a fan of using the second collection method as it avoids the possibility of ConcurrentModificationException when iterating via the index.

其他提示

The set method is probably what you are looking for:

import java.util.*;

public class IterDemo {
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList() {{
            add("one");
            add("two");
            add("three");
        }};

        System.out.println("Before: " + arrayList);

        ListIterator<String> iter = arrayList.listIterator();
        while(iter.hasNext()) {
            String s = iter.next();
            iter.set(s.toUpperCase());
        }

        System.out.println("After: " + arrayList);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top