Doubt with reference when using add in Linkedlist, java

Asked

Viewed 129 times

1

I have a LinkedList<CasosPossiveis> casos = new LinkedList<>(); and a CasosPossiveis objeto = new CasosPossiveis();. Within a for, after this statement, I make a: casos.add(objeto);, after modifying the object data. However, what happens is that when I print my casos, the values in all the positions in the list are equal because, it seems, objetowas passed as a reference in casos.add(objeto);. What I want to do is that every time I give a .add(objeto), a new value is added and not modified further if I modify the objeto. How can I do that?

Code of for:

for (int i = 0; i < texto.size(); i++) {
        String[] aux = texto.get(i).split(" ");

        if (aux.length > 2) {
            cont = 0;

            if (pratos.size() != 0) {
                System.out.println("ta diferente: " + pratos.size());
                objeto.setPratosPossiveis(pratos);
                System.out.println("um pratro add: ");

                casos.add(objeto); //PROBLEMA: ta recebendo sempre o edenreço de objeto e mudando tudo

                System.out.println(casos.get(0).getPratosPossiveis().get(0).get(0));


                pratos.clear();
            }

            objeto = new CasosPossiveis();
            System.out.println("NumerO2: "+objeto.getNumeroDias());
            objeto.setNumeroDias(Integer.parseInt(aux[0]));
            objeto.setNumeroPratos(Integer.parseInt(aux[1]));
            objeto.setOrcamento(Integer.parseInt(aux[2]));

        } else {
            pratos.add(new LinkedList<>());
            pratos.add(new LinkedList<>());
            System.out.println("Valor do cont: " + cont);
            pratos.get(cont).add(Integer.parseInt(aux[0]));
            pratos.get(cont).add(Integer.parseInt(aux[1]));
            System.out.println("o que adicionei 1: " + pratos.get(cont).get(0));
            System.out.println("o que adicionei 2: " + pratos.get(cont).get(1));
            cont++;
        }
    }
  }
    System.out.println("tamanho q ficou: " + casos.size());
    for (int i = 0; i < casos.size(); i++) {
        System.out.println("aqui: " + casos.get(i).getPratosPossiveis().size());
        for (int j = 0; j < casos.get(i).getPratosPossiveis().size(); j++) {
            System.out.println("ue");
            System.out.println(casos.get(i).getPratosPossiveis().get(i));
        }

    }

Explanation: texto.size() has data from a file. Each position is a file line. If the line has more than two ints, I add what I had on the object in my ArrayList of objects, "clean" the object and start adding values again to the object, until I find a new line with more and two ints.

  • The construction of the object has to come within the for so that they are all different, otherwise you are adding the same object in all the houses of the array

  • In Java, all objects are passed by reference. If you want to put a different object inside the list, you must create a new object, and not put the existing one again.

  • Before modifying the object values, inside the for, I make a objeto = new CasosPossiveis(); always. Still, it’s not working.

  • Then post your code for to better understand what happens.

  • Question edited with code.

  • texto is the type List<String[]>?

  • That. Text a string arraylist. Example of position 0 of text: 1 3 26. From position 1: 44 5843.

  • What is pratos? I think this one objeto.setPratosPossiveis(pratos); will do all the CasosPossiveis have the same list of dishes instead of giving a list of different dishes paara each.

  • Your System.out.println(casos.get(0).getPratosPossiveis().get(0).get(0)); will always take the first case. Maybe it should be System.out.println(objeto.getPratosPossiveis().get(0).get(0));?

  • Dishes is a matrix that is part of my object. When the line is larger than 2, I save the data from it. When it has size 2, I take the row data and save it to the matrix. Each row is a matrix position. Sometimes we have 3 or 4 rows in a row of size 2 without a new size 3 coming. When it comes, I clean the object and start all over again.

  • This Sout was just for testing, to see what was picking up in the first position. That’s not the problem. I will edit the code to show you how I am printing the values and see the error.

  • Instead of pratos.clear();, would not be the case to make a pratos = new ArrayList<>();? I guess there’s no point in destroying the list you just added to objeto and not have them all sharing the same destroyed list.

  • That is to say, pratos is an array of numbers with two columns and several rows?

  • Linkedlist<Linkedlist<Integer>> dishes = new Linkedlist<>();

  • Dude, I think I can solve the problem the way you said. Using pratos = new ArrayList<>();. Also, I’ve redone a lot on my for to make it clearer. I’m reading the text list differently. Thanks so much for the help.

  • At last System.out.println, you are using i twice instead of i and j.

Show 11 more comments

1 answer

1


Change the type of pratos for List<List<Integer>>. Try to do this:

    for (String linha : texto) {
        String[] aux = linha.split(" ");

        if (aux.length > 2) {
            objeto = new CasosPossiveis();
            System.out.println("Numero 2: " + objeto.getNumeroDias());
            objeto.setNumeroDias(Integer.parseInt(aux[0]));
            objeto.setNumeroPratos(Integer.parseInt(aux[1]));
            objeto.setOrcamento(Integer.parseInt(aux[2]));
            pratos = new ArrayList<>();
            objeto.setPratosPossiveis(pratos);
            casos.add(objeto);
        } else {
            int a = Integer.parseInt(aux[0]);
            int b = Integer.parseInt(aux[1]);
            List<Integer> linhaPratos = Arrays.asList(a, b);
            pratos.add(linhaPratos);
        }
    }
}

System.out.println("Tamanho que ficou: " + casos.size());
for (CasosPossiveis caso : casos) {
    System.out.println("aqui: " + caso.getPratosPossiveis().size());
    for (List<Integer> pratosPossiveis : caso.getPratosPossiveis()) {
        System.out.println("ue");
        System.out.println(pratosPossiveis);
    }
}

At last System.out.println, you were using i twice instead of i and j. However, using the syntax of Enhanced-for it becomes much easier to scroll through the list and avoid having to use that lot of indexes.

The variable cont can be eliminated.

  • It worked perfectly. I will certainly learn how to use Enanced-for. Thank you very much. PS.: is int b = Integer.parseint(aux[1]); haha

  • @Marcos Editado.

Browser other questions tagged

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