Does the clear() method in Java null the elements in ArrayList or just free its references and keep values alive.
I am assigning all objects in ArrayList to another object and then clearings it. After clearing it the assigned references to another objects are giving inconsistent results. On the other hand if I create a new ArrayList object instead of clearing it works fine.
ArrayList <Condition> conditionList = new ArrayList<Condition>();
Risk riskObject = new Risk();
for (int i =0; i<10; i++) {
if(some-condition){
addElemetsToConditionList();
}else{
addElemetsToConditionList();
riskObject.setConditions(conditionList); // Setter which sets condition list to risk object.
Risk newRiskObject = new Risk();
riskObject = newRiskObject;
// conditionList = new ArrayList<Condition>();
conditionList.clear();
}
}
Internally, it
null
s all the elements in it's backing buffer (removing the references that it has) and set it's size to0
Any references you might have to the data external are still valid, it's just the
ArrayList
no longer maintains a reference to themI believe your problem is here...
You're passing the instance of the
ArrayList
to theriskObject
and then clearing it, it is sharing the same instance.Instead, you could create a new instance of a
ArrayList
Which makes a copy of the contents of the
conditionList
, so when you clear it, the reference you passed toriskObject
won't be effected or, as you have already done, create a newArrayList
for your continuing processing, which ever seems most logical to you.