ArrayList adding wrong values

0

I have ArrayList that should be receiving numbers from 0 to 15, within for , however it seems that the last value 15 is being written to all indexes.

ArrayList <PaginaPrincipalSO> FilaTPSO= new ArrayList();
PaginaPrincipalSO TPSO = new PaginaPrincipalSO();

public void armazenarTPSO(PaginaPrincipalSO a){
    FilaTPSO.add(a);
}

public void preencherTPSO(){
    int NPF = retornaNPF();
    JOptionPane.showMessageDialog(null, NPF); //apenas para confirmar o valor de NPF que chega como 15
    for(int y=0;y<=NPF;y++){
        TPSO.setNPF(y);
        armazenarTPSO(TPSO);
    }
    for(int y=0;y<=NPF;y++){
        JOptionPane.showMessageDialog(null, FilaTPSO.get(y).getNPF()); //buscando os valores dentro do arraylist e recebendo como retorno sempre 15
    }

}
    
asked by anonymous 30.10.2014 / 23:32

1 answer

4

The problem is that you are always adding and changing the same object in the list, that is, it has a 16-position vector pointing to the same object.

The correct thing would be to instantiate and initialize a new object in each iteration, so that its logic does not overwrite the value of the objects.

Your code should be:

public void preencherTPSO(){
    int NPF = retornaNPF();
    JOptionPane.showMessageDialog(null, NPF); //apenas para confirmar o valor de NPF que chega como 15
    PaginaPrincipalSO localTPSO;

    for(int y=0;y<=NPF;y++){
        // Inicializa um novo Objeto para adicionar na lista.
        localTPSO = new PaginaPrincipalSO();

        localTPSO.setNPF(y);
        armazenarTPSO(localTPSO);
    }

    for(int y=0;y<=NPF;y++){
        JOptionPane.showMessageDialog(null, FilaTPSO.get(y).getNPF()); //buscando os valores dentro do arraylist e recebendo como retorno sempre 15
    }
}

And you do not need to keep a global instance any more.

    
30.10.2014 / 23:48