Write object on a list not the reference

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 can someone help me 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 in the list I see that the items are all repeated.

for (ModeloParcela v : modeloParcelas) {                    
System.err.println(format.format(v.getDataVencimento().getTime()));
}
    
asked by anonymous 04.10.2016 / 21:47

1 answer

0

When you hit the expiration date, ( setDataVencimento ), you pass the Calendar object reference.

To avoid this, use the clone()

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

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

Follow the clone documentation.     

04.10.2016 / 22:09