Using Java ruleSet properly
Considering this piece of code
for (MyRule cr : cr开发者_开发问答List) {
if (crIds.contains(cr.getParentId())) {
ruleSet.add(cr);
for (int cursor = 0; cursor < parentChildrenList.size(); cursor++) {
if (parentChildrenList.get(cursor).getId().equals(cr.getParentId())) {
parentChildrenList2.get(cursor).setChildRules(ruleSet);
parentChildrenList2.remove(cursor + 1);
}
}
}
ruleSet.clear();
}
When I do the ruleSet.clear()
I also lose the value I previously set in parentChildrenList2.get(cursor).setChildRules(ruleSet);
How can I stop losing it but in the same time clearing the ruleSet
?
Note that setChildRules()
(probably) doesn't create a copy of the Set
referenced by ruleSet
. It simply copies ("remembers") the reference to that Set
. If you later modify that Set
(such as calling clear()
) then this will be visible to everyone who has a reference to that Set
.
It seems like you want each element in parentChildrenList2
to have its own Set
. So you effectively need to replace ruleSet.clear()
with ruleSet = new HashSet()
(or whatever type you used).
精彩评论