Reputation: 11
I have a list, each object can contain child elements. I want to iterate recursively through each element and update the element if it contains some faulty value. The doUpdate method return true if it updated element.
The ddmUpdated parameter is false at the start
boolean updateRecursive(DDMFormField dDMFormField, List<DDMFormField> dDMFormFieldList, boolean ddmUpdated){
if(!ddmUpdated){
ddmUpdated = doUpdate(dDMFormField);
}else{
doUpdate(dDMFormField);
}
if(!dDMFormFieldList.isEmpty()){
for (DDMFormField fl: dDMFormFieldList){
ddmUpdated = updateRecursive(fl,fl.getNestedDDMFormFields(), ddmUpdated);
}
}
return ddmUpdated;
}
In the end I would like to return with true if I did some changes on least one element of the list. I don't know why, it always return false even if the doUpdate returned back with true and the recursion continued with ddmUpdated = true.
Can anyone suggest a correct way to keep the true value?
Upvotes: 0
Views: 304
Reputation: 76
You are overwriting the return value of the recursive calls in ddmUpdated. Make sure to only overwrite it if the value is true like this:
boolean updateRecursive(DDMFormField dDMFormField, List<DDMFormField> dDMFormFieldList, boolean ddmUpdated){
if(!ddmUpdated){
ddmUpdated = doUpdate(dDMFormField);
}else{
doUpdate(dDMFormField);
}
if(!dDMFormFieldList.isEmpty()){
for (DDMFormField fl: dDMFormFieldList){
ddmUpdated = ddmUpdated | updateRecursive(fl,fl.getNestedDDMFormFields(), ddmUpdated);
}
}
return ddmUpdated;
The or operator |
will return true if one of the arguments is true.
Upvotes: 0