I have been asked from my professor to add an object in the middle of an ArrayedList<Employee> using listiterator.
I have tried doing in the following way first:
ListIterator < Employee > li = emps.listIterator(emps.size());
System.out.println("\nUsing ListIterator:\n");
i = 1;
while (li.hasPrevious()) {
if (li.nextIndex() == 5) {
li.add(emp_M);
}
System.out.println(" Employee " + (i++) + " " + li.previous());
}
But this produces a seemingly infinite number of iterations where li.nextIndex() gets stuck on 5.
I have verified this with the debugger and this happens only after li.add(emp_M) is evaluated.
I have found a solution where I added a break right after li.add(emp_M) and continued parsing the list separately in the same way but without adding to the list emp_M at all:
//parse in two loops to add the middle employee, without the break the list seemingly spirals into infinity!
System.out.println("\nUsing ListIterator:\n");
i = 1;
while (li.hasPrevious()) {
if (li.nextIndex() == 5) {
li.add(emp_M);
System.out.println("ADDED IN MIDDLE");
break;
}
System.out.println(" Employee " + (i++) + " " + li.previous());
}
while (li.hasPrevious()) {
System.out.println(" Employee " + (i++) + " " + li.previous());
}
This left me wondering, is what I did a lazy and naive approach? How else can I add to a list with listIterator?