Why can’t I access the elements inside an Arraylist with a for?

Asked

Viewed 173 times

1

I’m trying to fill a jtable with elements that are inside an arraylist, which is inside another object:

private void jButtonConfirmarProdutoActionPerformed(java.awt.event.ActionEvent evt) {                                                        
    modProduto.setQuantidade(Integer.parseInt(jTextFieldQnt.getText()));
    modVenda.itens.add(modProduto);
    jTable1 = ctrl.fillTable(jTable1, modVenda);
}   

These are the classes:

public class ModeloVenda {

    private int idVenda;
    private String data;
    private float valorVenda;
    private int idCliente;
    public final ArrayList<ModeloProduto> itens;
}

public class ModeloProduto {
    private int id_produto;
    private String nome;
    private float preco_compra;
    private float preco_venda;
    private int quantidade;
    private int fornecedor;

public float calculaTotal(int quantidade){
    return preco_venda*quantidade;
}}

This is the function that fills the table:

public JTable fillTable(JTable tabela, ModeloVenda mod){
    ArrayList data = new ArrayList();
    String[] Collums= new String[]{"Nome", "Valor Unitário", "Quantidade", "Valor Total"};
    for(int i = 0; i < mod.itens.size(); i++){
        dados.add(new Object[]{mod.itens.get(i).getNome(), 
            mod.itens.get(i).getPreco_venda(), mod.itens.get(i).getQuantidade(), 
            mod.itens.get(i).calculaTotal(mod.itens.get(i).getQuantidade())});
    }
    ModeloTabela modelo = new ModeloTabela(dados, Colunas);
    tabela.setModel(modelo);

    for(int i = 0; i<Colunas.length; i++){
        tabela.getColumnModel().getColumn(i).setPreferredWidth(150);
        tabela.getColumnModel().getColumn(i).setResizable(false);
    }
    tabela.getTableHeader().setReorderingAllowed(false);
    tabela.setAutoResizeMode(tabela.AUTO_RESIZE_OFF);
    tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    return tabela;
}

But when I add another element in the array and update the table all elements are replaced by the new: First Element Added Second Element Added

  • your problem is in the jButtonConfirmarProdutoActionPerformed, you have to create a new modProduto for every time you add it to the list. You’re adding the same item over and over again without ever creating the new one, and even worse, you’re changing it over the course of the code

  • @Sorack, thank you, that solved the problem, I thought the function arraylist.add created a new object and passed the parameters, not that it used the same object. Thank you

  • @Sorack now that the question has reopened, it would be interesting to post your comment as an answer, to "close" the question as solved.

  • @diegofm posted the reply, thank you!

1 answer

2

Let’s assume you have an item class:

public class Item {

  String descricao;

  public String getDescricao() {
    return descricao;
  }

  public void setDescricao(String descricao) {
    this.descricao = descricao;
  }

  @Override
  public String toString() {
    return this.descricao;
  }
}

And have the following method:

List<Item> itens = new ArrayList<>();
Item item = new Item();

item.setDescricao("Descrição A");
itens.add(item);
item.setDescricao("Descrição B");
itens.add(item);
item.setDescricao("Descrição C");
itens.add(item);

System.out.println(itens);

The exit would be:

[Description C, Description C, Description C]

Why?

Because you only once instated each item, so by changing some property you just changed the original item and replicated the references to this same item in your list.

And how to solve?

The correct way would be to create an instance for each item as follows:

List<Item> itens = new ArrayList<>();

Item itemA = new Item();
itemA.setDescricao("Descrição A");
itens.add(itemA);
Item itemB = new Item();

itemB.setDescricao("Descrição B");
itens.add(itemB);

Item itemC = new Item();
itemC.setDescricao("Descrição C");
itens.add(itemC);

System.out.println(itens);

Where the exit would be:

[Description A, Description B, Description C]

And where does that fit into the problem?

In the method jButtonConfirmarProdutoActionPerformed, you have to create a new modProduto for each time you add to the list otherwise it will be, just as in the example, just replicating the reference to a single object.

Browser other questions tagged

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