Skip to content
Advertisement

How to add an object during ListIterator (reversed) iteration properly?

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?

Advertisement

Answer

The problem in your code is that you will add the element emp_M indefinitely.

If we go through one iteration where you add an element:

Suppose li.nextIndex() == 5, then you will add a new element to your iterator, and according to the documentation of add, you will also increase by one your index (hence you move your iterator to the right). Then your loops continues and you move your iterator to the left with li.previous(), which happens to be place before you added the element (and verifies the if condition to add).

Now, you start a new iteration of your while loop, verifies the condition again, add a new element ect… You will stay stuck at the element verifying the condition by adding indefinitely new elements.

To make the code easier, try to run your iterator in the documentation direction (ie e1 -> e2 -> e3 -> e4)

ListIterator < Employee > li = emps.listIterator();

i = 1;
while (li.hasNext()) {
    if (li.nextIndex() == 5) {
        li.add(emp_M);
    }

    System.out.println("  Employee " + (i++) + " " + li.next());
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement