I've got an object of type DocObject that contains an arraylist of DocObjects within it called children, each of which may or not contain children themselves. I'm writing a function for this object called replace() that takes a child to be searched for, and if the DocObject contains that child then the child should be replaced with newObj. I have looked around the site and searched google but nothing I've seen is working. The code below shows what I've tried:
public void replace(DocObject oldObj, DocObject newObj) {
for (DocObject child : children ) {
if (child == oldObj) {
child = newObj;
}
}
}
And this (this causes an overflow exception):
public void replace(DocObject oldObj, DocObject newObj) {
if (children.indexOf(oldObj) != -1)
children.set(children.indexOf(oldObj), newObj);
for (DocObject child : children)
child.replace(oldObj, newObj);
}
This isn't replacing the child, however, and I have checked to see that the if statement is working correctly and its condition met. How can I replace oldObj with newObj?
I would not recommend looping using the for (X x: thingWithXs) construct while manipulating the list. I would recommend using indexOf to search for the desired object and if it cannot be found, recursively calling replace on the children of the object you are looking at.
Note that you'll have to modify your replace method to accept the list of objects as an argument:
public boolean replace(List<E> list, E oldE, E newE) {
if (list == null) {
return false;
}
int index = list.indexOf(oldE);
if (index > 0) {
list.set(index, newE);
return true;
}
for (int i = 0, l = list.size(); i < l; i++) {
List<E> children = list.get(i).children;
if (replace(children, oldE, newE)) {
return true;
}
}
return false;
}
Disclaimer: The above code has not been tested. It should give you an idea as to how it can be done. Essentially what it comes down to is checking if the element you are looking for is in the list, and if not, iterating over the list and checking each set of children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With