How do I remove a object and all this children

I have a class Block that extends Node



I want to create a method that destroys the object

inside itself

[java]

if(this instanceof MasterBlock){



this.removeControl(RigidBodyControl.class);

this.setDeathTimer(0);

System.out.println("Destroy" + this.getName() + getMasterId());

ScriptBlocksApplication.getInstance().getMasterBlockMap().remove(this);

ScriptBlocksApplication.getInstance().getRootNode().detachChild(this);

for(Spatial spatial : this.getChildren()){

this.detachChild(spatial);

}



this.setScriptEvaluator(null);

}else{

((Block)this.getParent()).detachChild(this);

}



[/java]



if i do it this way it gives me a Exception

java.util.ConcurrentModificationException

at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)

at java.util.AbstractList$Itr.next(AbstractList.java:343)

at com.blocks.blocks.Block.destroy(Block.java:471)



If I dont do the

[java]

for(Spatial spatial : this.getChildren()){

this.detachChild(spatial);

}

[/java]



the spatial will remain on the screen.



Any Ideas?



-Greg

Simple solution

[java]ArrayList<Spatial> childrenList = getChildren().clone();

for(Spatial spatial : childrenList){

detachChild(spatial);

}[/java]

1 Like

Thanks I had to do this

ArrayList childrenList = (ArrayList)((ArrayList) this.getChildren()).clone();



so i would compile



but it worked



-Greg

You are probably better off (and certainly more future proof) if you just instantiate a new ArrayList and pass the children on the constructor. I’d be very much surprised if it is slower than clone and it is certainly a million times safer.

[java]List<Spatial> childrenList = new ArrayList<Spatial>( getChildren() );[/java]



That way if the internal implementation of getChildren() ever changes your code won’t break.