Problem with displaying data in ArrayList

3

I have a problem with displaying data in 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 years old Name: Luis Age: 19

    
asked by anonymous 24.09.2015 / 00:41

1 answer

4

Dude, it seems that because you are using the same variable (p) to insert, you are entering the same variable all the time, then you modify it and automatically modify the entire list. Try it as soon as you insert another person, so:

p = new Pessoa();

and proceed with the program, so you are creating another object, okay? Thanks.

    
24.09.2015 / 00:49