Arraylist adding undue values

Asked

Viewed 71 times

0

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

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
    }

}
  • I’m not seeing any problems. Is it somewhere in the code that you’re not showing? You’re creating 16 elements in the array?

  • The problem is that it always adds the same object, rather than instantiating one at each iteration.

  • this, are 16 elements. I am just putting here, because it does not seem to have errors and this part of the code is independent of the others at first. But when I spin the last I always get 15.

  • You think you would have to do this every time: Paginaprincipalso TPSO = new Paginaprincipalso();

  • CORRETO @Wakin. It worked... As I appreciate your reply, since it was a comment?

  • @Wakim good, I ate ball in this.

Show 1 more comment

1 answer

4


The problem is that it is 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 one would be to instantiate and initialize a new object in each iteration, so that its logic does not override the value of the objects.

Your code should stay:

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 don’t need to maintain a global instance anymore.

Browser other questions tagged

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