[jdom-interest] Removing 'Element's from a list during iteration

Alastair Rodgers alastair.rodgers at PHOCIS.COM
Tue Dec 11 07:01:38 PST 2001

I'm using an Iterator to navigate a list of child elements. As I do this, I want to remove certain of these children from the JDOM tree based on whether or not some attribute is present. Since Element.getChildren(String) returns a "live" list, I had expected to be able to do this with Iterator.remove() as follows: 

    Element elBase = ...
    for (Iterator iter = elBase.getChildren("SomeElement").iterator(); iter.hasNext(); ) {
      Element el = (Element)iter.next();
      if (el.getAttributeValue("SomeAttribute") == null) {

However, I find that after calling iter.remove() if I look at the parent of 'el', it is still elBase, i.e. it hasn't been properly detached. If I replace the call to "iter.remove()" with "el.detach()" (which has the effect of invoking elBase.removeContent(el)) then it appears to work - el's parent is now null. However, this violates the general usage pattern of Iterator, as the following extract from the Javadoc for Iterator.remove() illustrates: 

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

Is this the expected behaviour? If so, is it safe for me to substitute el.detach() in the above example, and ignore the J2SE Javadoc? 

Thanks in advance, 

More information about the jdom-interest mailing list