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.