Prevent object from replacing others in Arraylist

Asked

Viewed 89 times

-1

I have two loops that have the function of replacing texts with other values.

The problem starts when I have an object added to a ArrayList, in the case the object clone. The addition is in the second loop because the system generates different result for each ingrediente.

To the line clone.getF().setCalculo(tempA); everything happens normal, but when it goes to the line novosItems.add(contaItem, clone); everything starts to go wrong.

The object clone which is being added replaces all objects contained in the ArrayList. Strangely only with a value that occurs this error. To illustrate what happens see this example:

//Um arrayList comum 
ArrayList<objeto> lista = new ArrayList<>();
//valores do arrayList lista
[0] = "Maria", "12"
[1] = "João", "10"
[2] = "Carlos", "33"

Now imagine that every time you add something new to ArrayList all values that would be the name for example become the same value of the last entered, but ages do not change.

lista.add("Roberto")
[0] = "Roberto", "12"
[1] = "Roberto", "10"
[2] = "Roberto", "33"
[3] = "Roberto", "22"

Below is the code that has this problem.

for (Item item : this.tabela.getItem()) {
    // Ingredientes
    final String[] formulainicial = item.getF().getCalculo().clone();
    Item clone = item;

    for (Ingrediente ingrediente : this.tabela.getIngredite()) {

        String tempA[];
        tempA = formulainicial.clone();

        //Subistitue o nome do ingrediente pelo seu valor
        for (int i = 0; i < formulainicial.length; i++) {
            // Procura por nutrientes que contem o mesmo nome e subistitue por valor do nutriente.,
            for (Nutriente n : nuts) {
                if (formulainicial[i].equalsIgnoreCase(n.getNome())) {
                    tempA[i] = String.valueOf(n.getQuantidade());
                }
            }

            if ("MO".equalsIgnoreCase(formulainicial[i])) {
                //Subistitue o texto "MO" pelo valor correspondente.
                tempA[i] = String.valueOf(ingrediente.getQuantidadedeMO())+"";
            }

            if ("total".equalsIgnoreCase(formulainicial[i])) {
                tempA[i] = String.valueOf(totaldeMO);
            }
        }

        listaF.add(contaItem, tempA);
        clone.getF().setCalculo(tempA);
        novosItems.add(contaItem, clone);
        contaItem++;
    }
}

1 answer

0


If this is happening it can be two things, either you are passing reference from the same object to the Arraylist or you are passing different but identical objects. I believe that is the second option and that the problem is in this line of code:

clone.getF().setCalculo(tempA);.

Now it becomes difficult to state with certainty without knowing how the methods getF() and setCalculo() implemented. You can post their code?

Another tip I give is to try to unlock this algorithm of yours in methods that return the value you want, the way it is is very confusing to understand what is happening and makes it difficult to maintain and test your code. The more isolated the logical blocks, the more object oriented your code will be

For example, replace this:

for (int i = 0; i < formulainicial.length; i++) {
        // Procura por nutrientes que contem o mesmo nome e subistitue por valor do nutriente.,
        for (Nutriente n : nuts) {
            if (formulainicial[i].equalsIgnoreCase(n.getNome())) {
                tempA[i] = String.valueOf(n.getQuantidade());
            }
        }

        if ("MO".equalsIgnoreCase(formulainicial[i])) {
            //Subistitue o texto "MO" pelo valor correspondente.
            tempA[i] = String.valueOf(ingrediente.getQuantidadedeMO())+"";
        }

        if ("total".equalsIgnoreCase(formulainicial[i])) {
            tempA[i] = String.valueOf(totaldeMO);
        }
    }

For something more like this:

    // Procura por nutrientes que contem o mesmo nome e subistitue por valor do     nutriente.,
public String substituiNutrientes(String formula){
    for (Nutriente n : nuts) {
                if (formula.equalsIgnoreCase(n.getNome())) {
                    return String.valueOf(n.getQuantidade());
                }
            }
    if ("MO".equalsIgnoreCase(formula)) {
                //Subistitue o texto "MO" pelo valor correspondente.
                return  String.valueOf(ingrediente.getQuantidadedeMO())+"";
            }
    if ("total".equalsIgnoreCase(formula)) {
                return String.valueOf(totaldeMO);
            }    
    return null; 
}


for (int i = 0; i < formulainicial.length; i++) {

    String formulaSubstituida = substituiNutrientes(formula)

    if(formulaSubstituida != null)tempA[i]  = formulaSubstituida;         

}

Browser other questions tagged

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