I have LinkedList<CasosPossiveis> casos = new LinkedList<>();
and CasosPossiveis objeto = new CasosPossiveis();
.
Within for
, after this declaration, I make a: casos.add(objeto);
, after modifying the object data. What happens, however, is that when I start my casos
, the values in all the positions in the list are the same because it seems that objeto
was passed as a reference in casos.add(objeto);
.
What I want to do is that every time I give .add(objeto)
, a new value is added and not modified any more, if I modify the objeto
.
How can I do this?
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 int
s, I add what I had in the object in my ArrayList
of objects, "clean" the object and start adding values back into the object until I find a new line with more and two int
s.