[jdom-interest] Sorting JDOM lists

Rolf Lear rlear at algorithmics.com
Mon Mar 8 04:44:30 PST 2004

Collections.sort() does not do a Element.detatch()....

What it does do is represent all the Elements as an array, then sorts them,
then iterates through the original list and set()'s each position in the
list to the corresponding value in the sorted array.

An element that moves from the end of the list to the beginning of the list
will temporarily be part of the list in two places. This breaks the
structure of JDom.

To make Collections.sort() work on ContentList, it would have to manually
detach Elements itself before adding them again.


-----Original Message-----
From: jdom-interest-admin at jdom.org
[mailto:jdom-interest-admin at jdom.org]On Behalf Of Chris B.
Sent: Monday, March 08, 2004 4:50 AM
To: Jason Hunter
Cc: jdom-interest at jdom.org
Subject: Re: [jdom-interest] Sorting JDOM lists

Jason Hunter wrote:

> Elements have parentage and can only have one parent at a time.  
> Sorting in place can require an element to have two parents for a time.

Sorting could never change the parent. It just tries to add it in the 
array at a different location.

> The easy solution is to detach the elements, then reinsert in sorted 
> order.
> List l = elt.removeContent();
> sort(l);
> elt.addContent(l);
> Feel free to tell us now how we should have done this differently.  :-)

Well... why throw the error when the parent hasn't changed?

> -jh-
> Chris B. wrote:
>> Is there any reason why JDOM won't allow you to sort a list of 
>> Elements??
>> Element el...
>> java.util.List items = (java.util.List)el.getChildren("aaaa", ns);
>> Collections.sort(headeritems, new Comparator() {
>>    ......
>> });
>> org.jdom.IllegalAddException: The element already has an existing 
>> parent "email:headers"
>>    at org.jdom.ContentList.add(ContentList.java:177)
>>    at org.jdom.ContentList.add(ContentList.java:138)
>>    at org.jdom.ContentList.set(ContentList.java:679)
>>    at org.jdom.ContentList$FilterListIterator.set(ContentList.java:1142)
>>    at java.util.Collections.sort(Collections.java:159)
>> _______________________________________________
>> To control your jdom-interest membership:
To control your jdom-interest membership:

More information about the jdom-interest mailing list