[jdom-interest] detach() from element

Tatu Saloranta cowtowncoder at yahoo.com
Wed Mar 23 08:37:05 PST 2005


--- "Bradley S. Huffman" <hip at a.cs.okstate.edu> wrote:
> kandryc at miser.umass.edu writes:
> > However, when I execute the following code:
> > 
> > List my_lists =
> theDocument.getRootElement().getChildren();
> > for (int i = 0; i < my_lists.size(); i++) {
> >    Element next = (Element)my)lists.get(i);
> >       if
> (next.getAttribute("refid").getValue().equals("1"))
> {
> >          next.detach();
> >       }
> > }
> > 
> > The output XML is:
> > 
> > <my-lists>
> >    <list refid="1" date="3/22/2005 4:14 PM" />
> >    <list refid="1" date="3/22/2005 6:01 PM" />
> >    <list refid="2" date="3/22/2005 6:23 PM" /> 
> > </my-lists>
> > 
> > Why are not all the elements with refid="1" not
> detached?
> 
> Because when you remove a item from a list, all
> items following it
> are shifted. For example if when i == 3 the if
> statement is true,
> the 3rd element is removed and the old 4th element
> becomes the new
> 3rd, the old 5th becomes the new 4th, etc, etc. Then
> the loop ends
> and i is incremented to 4, leaving what was the old
> 4th element untouched.

This is probably true, but what confuses many people
is that result sets are live (if they are). In this
case, for example, he does NOT call list.remove(), but
listItem.detach(), so behaviour could actually be
different (for non-live result sets, List would just
be a copy and detach() would just modify tree, not
List).

Is there an FAQ entry that explains this? It's fairly
straight-forward once you know the behaviour, but
otherwise confusing.

-+ Tatu +-




		
__________________________________ 
Do you Yahoo!? 
Yahoo! Small Business - Try our new resources site!
http://smallbusiness.yahoo.com/resources/ 


More information about the jdom-interest mailing list