[jdom-interest] Problems with Collections.sort(List,Comparator)

Jason Hunter jhunter at servlets.com
Wed Apr 10 12:10:28 PDT 2002


The problem is that the sort algorithm in moving the elements around
will sometimes place an element in its new location without first
removing it from its previous location, and that causes the document to
complain because the element is being attached twice.  You need to
remove the elements' parents before the sort.  I think the following
would work (untested).  Someone else probably has something more
elegant.  If so, please write in so I can put this in the FAQ.

List list = element.getChildren();   // get kids
List listCopy = new ArrayList(list); // get shallow copy
Collections.sort(listCopy, new ContentTagComparator()); // sort copy
element.setContent(null);            // clear parentage
element.setChildren(listCopy);       // add cleanly

-jh-

> Marcel Heuzer wrote:
> 
> Hi,
> 
> When I try to sort a list of children with this code:
> 
> 
>   public Element getListSortedByString(Element element) {
> 
>     try {
>       List list = element.getChildren();
>       Collections.sort(list, new ContentTagComparator());
>       element.setChildren(list);
>     }
>     catch(Exception e) {
>       e.printStackTrace(System.out);
>     }
>     return element;
> 
>   }
> 
>   public class ContentTagComparator implements Comparator {
> 
>     public int compare(Object o1,Object o2) {
> 
>       String s1 = ((Element)o1).getText();
>       String s2 = ((Element)o2).getText();
>       int result = s1.compareTo(s2);
>       return result;
>     }
> 
>   }
> I get this exception at the end of Collections.sort(list, new
> ContentTagComparator()); process:
> 
> org.jdom.IllegalAddException: The element already has an existing
> parent
>  at org.jdom.ContentList.add(ContentList.java:190)
> 
>  at org.jdom.ContentList.add(ContentList.java:146)
> 
>  at org.jdom.ContentList.set(ContentList.java:663)
> 
>  at org.jdom.ContentList$FilterListIterator.set(ContentList.java:1150)
> 
>  at java.util.Collections.sort(Unknown Source)
> 
> 
> 
> Is it a bug ?
> Is there another way to sort elements content ?
> 
> Thanks
> 
> Marcel Heuzer
>



More information about the jdom-interest mailing list