Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I have found it after digging deeper in the debugger.

At the moment before adding li.nextIndex() == 5 and li.previousIndex() == 4 After adding the object the aforementioned change to li.nextIndex() == 6 and li.previousIndex() == 5 this is because listIterator's .add() inserts the object before .next().

Moving ahead with this problem sets up a back and forth loop where li.previous() decreases both li.previousIndex() and li.nextIndex() by 1, and calling li.add(emp_M) increases both aforementioned values by 1.

To fix it, we need to skip the added element after adding:

 System.out.println("\nUsing ListIterator:\n"); 
        i = 1;
        while (li.hasPrevious())
        {
            if(li.nextIndex() == 5)
            {
                li.add(emp_M);
                li.previous();
                System.out.println("ADDED IN MIDDLE");
//              break;
            }
            System.out.println("  Employee " + (i++) + " " + li.previous());
        }

this effectively negates the problem mentioned above.

Sometimes by simply asking a question you find the answer yourself!

I'm going to delay accepting my own answer if someone can explain it to me better than I understood it.

over 4 years ago · Santiago Trujillo Report

0

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());
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!