I am using ListIterator to iterate in the list as I want to add few elements during runtime if certain conditions are met.
But the new elements that are added to the list are never included in the iterator
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Example {
public static void main(String[] s)
{
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(5);
list.add(6);
ListIterator<Integer> listIterator = list.listIterator();
while(listIterator.hasNext())
{
int i = listIterator.next();
System.out.println("List Element: " + i + " | List size: " + list.size());
if(i==1)
{
//Adding '3' to list
listIterator.add(3);
System.out.println("Added Element: 3");
}
if(i==2)
{
//Adding '4' to list
listIterator.add(4);
System.out.println("Added Element: 4");
}
}
}
}
Below is the output
List Element: 1 | List size: 4
Added Element: 3
List Element: 2 | List size: 5
Added Element: 4
List Element: 5 | List size: 6
List Element: 6 | List size: 6
I need to make use of the recently added element in current listIterator but not able to do it.
Is there any other way to iterate over the new elements in the same iteration session?
We can use for
loop to iterate and add elements to end of the loop at the same time
for (int i = 0; i < list.size(); i++) {
int element = list.get(i);
if(element == 1){
System.out.println(element);
list.add(3);
}
else if(element == 2){
System.out.println(element);
list.add(4);
}
else
System.out.println(element);
}
System.out.println(list);
Output:
1
2
5
6
3
4
[1, 2, 5, 6, 3, 4]