Removing children from node

I have to remove many children from a node based on a condition. My first attempt was with a for loop:

[java]

for(Spatial child : node.getChildren()) {

if(conditionTrue)

child.removeFromParent();

}

[/java]



For this attempt I got a ConcurrentModificationException error. So for attempt 2 I used an iterator:

[java]

Iterator<Spatial> iter = pitNode.getChildren().iterator();

while(iter.hasNext()) {

Node child = (Node) iter.next();

if(conditionTrue)

iter.remove()

}

[/java]



This does what I need but will there be any side effect/problem later on for not using removeFromParent()?

Possibly it will be helpful:



http://hub.jmonkeyengine.org/groups/physics/forum/topic/detaching-child-and-collision/

Thanks for the reply, I actually had that same problem earlier but managed to fix it, but it’s not really the issue here. I’m not really having any problems now, I just want to know if there is a problem with removing a node by not using the removeFromParent() method, e.g. with the iterator.remove() method.



As far as I know iterator.remove() just takes the item and removes it from the list and removeFromParent() does some other stuff that iterator.remove() doesn’t do. Will my program be affected because it doesn’t do the stuff that removeFromParent() does.

You are probably right to be concerned since removing the child from the list (at least from my interpretation of the code) doesn’t do any of the normal detach stuff.



The way I see it, you have two options.



[java]

List<Spatial> children = new ArrayList<Spatial>( pitNode.getChildren() );



…use your first loop but on children.

[/java]



Or if shallow copying the child list bothers you:



[java]

for( int i = 0; i < pitNode.getQuantity() ; i++ ){

if( condition ) {

pitNode.detachChild(i);

i–; // since the list just got smaller

}

}

[/java]



…or something like that. Considering all of the times that the internal list will be copied just to remove the single elements, the first approach is not as inefficient as it looks… what’s one extra copy after all? :slight_smile:



It probably wouldn’t be that hard to make jME return a list that properly updates the parent when children are removed but I don’t think it’s been anyone’s priority. It’s definitely more code for something that I guess doesn’t come up too often.

Cool, thanks for clearing that up and the solution. It seems like something I should have known considering I was reading about similar stuff a few days ago :stuck_out_tongue: