Problem with showing data in Arraylist

Asked

Viewed 64 times

3

I have a problem to show the data in the arraylist, it always shows the duplicate result

public static void main (String[]args){
   Scanner ler=new Scanner(System.in);
   Pessoa p=new Pessoa();

ArrayList<Pessoa> listaDePessoas= new ArrayList<>();   

    System.out.println("Digite o seu nome: ");
    p.setNome(ler.nextLine());
    System.out.println("Digite sua idade: ");
    p.setIdade(ler.nextInt());
    listaDePessoas.add(p);
    ler.nextLine();
    System.out.println("Digite o seu nome: ");
    p.setNome(ler.nextLine());
    System.out.println("Digite sua idade: ");
    p.setIdade(ler.nextInt());
    listaDePessoas.add(p);

    for(int i=0;i<listaDePessoas.size(); i++){
        System.out.println("Nome: "+listaDePessoas.get(i). getNome());
        System.out.println("Idade: "+listaDePessoas.get(i). getIdade());
    }

result: Name: Luis Age: 19 Name: Luis Age: 19

1 answer

4

Dude, it seems like because you’re using the same variable (p) to insert, you’re inserting the same variable all the time, then you modify it and automatically modify the whole list. Try it once you insert someone else do so:

p = new Pessoa();

and proceed with the program, so you’re creating another object, okay? Hug.

  • That’s right! p is a reference. Therefore, in a simplified way, any change made in p will reflect everywhere where this such p is referenced, in this case, all items within the ArrayList.

Browser other questions tagged

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