I first noticed this problem when I only put the objects in listOfRates and then created inverseListOfRates by copying it. But even using this method, I can't alter one list without altering the other.
How do I solve this issue?
List<HistoricRate> listOfRates = new ArrayList<HistoricRate>();
List<HistoricRate> inverseListOfRates = new ArrayList<HistoricRate>();
for (HistoricRate rate : rates){
listOfRates.add(rate);
inverseListOfRates.add(rate);
}
inverseListOfRates.forEach(r -> r.setMid(1 / r.getMid()));
The two lists are referencing the same object. So if you change the first, the second will change also.
The solution is to clone the object (Creating a copy of it into a new instance) before adding it into the second list.
To clone the object you can either use one of the following suggestions:
1- A constructor by copy :
class HistoricRate {
private String field;
public HistoricRate (HistoricRate another) {
this.field= another.field; // you can access
}
}
2- HistoricRate must implement Cloneable interface
Implement the method clone to copy the object.
3- Use org.apache.commons.lang.SerializationUtils as below :
for (HistoricRate rate : rates){
listOfRates.add(rate);
inverseListOfRates.add(SerializationUtils.clone(rate));
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments