Save object to a list not the reference

Asked

Viewed 48 times

0

The problem is the following I try to save the object in a List and what happens is that it saves the reference not the object someone can help me to solve this problem?

ArrayList<ModeloParcela> modeloParcelas = new ArrayList<ModeloParcela>();
for (int i = 1; i < quantidade; i++) {
ModeloParcela modeloParcela = new ModeloParcela();

calendarTemp.add(calendarTemp.MONTH, 1);
System.err.println(result[0]);
modeloParcela.setDataVencimento(calendarTemp);
modeloParcela.setValor(result[0]);      
modeloParcelas.add(retorno(modeloParcela));
}

When I show the data of the list I see that the items are all repeated.

for (ModeloParcela v : modeloParcelas) {                    
System.err.println(format.format(v.getDataVencimento().getTime()));
}
  • could show the method return ???

  • I edited and put how I’m showing the data.

  • Not knowing what the return method does gets a little complicated.

1 answer

0

When you set the due date, (setDataVencimento ), you pass the object reference Calendar.

To avoid this, use the method clone()

In this case, it returns a Object, then we cast a cast:

 modeloParcela.setDataVencimento( Calendar.class.cast(calendarTemp.clone()) );

Follow the documentation from clone.

  • It didn’t go very well here no but thanks for the tip.

  • What happens? Could show the method return ?

Browser other questions tagged

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