Inserting items into an Arraylist does not work as expected

Asked

Viewed 123 times

0

I need to add an item to the list 9 times, only when I print, only the data appears 12 , "Oi", "Aline". What am I doing wrong?

package webservice;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
public class LivroResource{

public static void main(String[] args) {

    int i = 10;
    List<Livro> livros = null;
    Livro livro;
    while(i != 0){

        livros = new ArrayList<>();
        livro = new Livro();

        livro.setId(12);
        livro.setTitulo("Oi");
        livro.setAutor("Aline");
        livros.add(livro);
        i--;
        System.out.println(i);

    }

    for(Livro biblioteca : livros){

    System.out.println(biblioteca.getId());
    System.out.println(biblioteca.getAutor());
    System.out.println(biblioteca.getTitulo());
    }
  }
}

1 answer

5


Remove this line from the loop, each iteration, you are creating a new list and deleting the previous one:

  livros = new ArrayList<>();

Leave it at that:

public static void main(String[] args) {

    int i = 10;
    List<Livro> livros = new ArrayList<>();
    Livro livro;
    while(i != 0){

        livro = new Livro();

        livro.setId(12);
        livro.setTitulo("Oi");
        livro.setAutor("Aline");
        livros.add(livro);
        i--;
        System.out.println(i);

    }

    for(Livro biblioteca : livros){

    System.out.println(biblioteca.getId());
    System.out.println(biblioteca.getAutor());
    System.out.println(biblioteca.getTitulo());
    }
  }
}

I believe that the condition of the tie, although it works, is not the most suitable for the situation, since you want to fill 10 positions decreasing. while(i > 0) has the same effect and makes the code more understandable.

  • It worked out! Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.