I am trying to iterate through a list using listiterator using previous method. In the loop If I try to add elements using listiterator.add method the loop is getting iterated infinitely
I tried to debug the code but I couldn't find the exact reason
public static methodOne() {
List l = new ArrayList();
for(int i = 0; i < 5; i++) {
l.add(i);
}
ListIterator li = l.listIterator();
while(li.hasNext()) {
li.next();
}
while(li.hasPrevious()) {
Integer i = (Integer)li.previous();
li.add(56);
}
System.out.println(l);
}
I expect the output to be 56,0,1,56,2,56,3,56,4,56,5
Your last loop runs infinitely because you keep adding an element and checking if it has previous. Of course it has previous, the one that you just added.
You can achieve what you want by:-
Output