Skip to content
This repository

JDOM2 Feature Element.sort_Comparator 

rolfl edited this page · 1 revision

JDOM Content is stored with a reference to the Content's parent. JDOM ensures that the tree structure of the JDOM content is always valid, and one of the validation rules ensures that a Parent instance cannot have two copies of any one child Content.

While this makes sense, it also is a problem if you want to sort the child Content of an Element. The issue is that the java.util.Collections.sort(*) methods use an algorithm that tends to 'set' the content in the 'target' position before 'removing' the Content from it's pre-sorted position. This results in a JDOM validation Exception.

The JDOM code has previously shipped a 'contrib' jar which contains a JDOM-safe sort algorithm.

JDOM2 has re-implemented the sort algorithm directly in to the Element class, and has done it using a Generic-friendly (well, not necessarily friendly, but consistent with java.util.Collections, and java.util.Comparator). The new methods on Element are:

  • Element.sortContent(Comparator<? super Content>) - sorts all the child content (mirrors Element.getContent() )
  • Element.sortChildren(Comparator<? super Element>) - sorts all the child Element content (mirrors Element.getChildren() )
  • Element.sortContent(Filter<E>, Comparator<? super E>) - sorts just the child content that matches the Filter (mirrors Element.getContent(Filter) )
  • Element.sortAttributes(Comparator<? super Attribute>) - sorts the Attributes of the Element

The sorting algorithm is customized to match the rules for JDOM, and in particular special attention should be paid to the following:

  • Child content that does not match the sorted set (non-Elements for sortChildren(...), and non-matching content for sortContent(Filter), ...) is not altered in any way. The best way to describe this is that for any non-sorted child content kid, then Element.indexOf(kid) will be the same before and after sorting (but will/may change for any sorted child content).
  • Child content that is sorted will not be 'detached' during the sort. The sort is done 'in place'.
  • Like all other core JDOM methods, the sort of Element child content is not thread-safe.
Something went wrong with that request. Please try again.