Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda