*/
public void setComparator(Comparator<? super E> comparator) {
// save this comparator
this.comparator = comparator;
// keep the old trees to construct the reordering
IndexedTree previousSorted = sorted;
// create the sorted list with a simple comparator
Comparator treeComparator = null;
if(comparator != null) treeComparator = new SortedListWithIndexedTree.IndexedTreeNodeComparator(comparator);
else treeComparator = new SortedListWithIndexedTree.IndexedTreeNodeRawOrderComparator();
sorted = new IndexedTree<IndexedTreeNode>(treeComparator);
// create a list which knows the offsets of the indexes to initialize this list
if(previousSorted == null && unsorted == null) {
unsorted = new IndexedTree<IndexedTreeNode>();
// add all elements in the source list, in order
for(int i = 0, n = source.size(); i < n; i++) {
IndexedTreeNode unsortedNode = unsorted.addByNode(i, IndexedTreeNode.EMPTY_NODE);
insertByUnsortedNode(unsortedNode);
}
// this is the first sort so we're done
return;
}
// if the lists are empty, we're done
if(source.size() == 0) return;
// rebuild the sorted tree to reflect the new Comparator
for(IndexedTreeIterator i = unsorted.iterator(0); i.hasNext(); ) {
IndexedTreeNode unsortedNode = i.next();
insertByUnsortedNode(unsortedNode);
}
// construct the reorder map
int[] reorderMap = new int[size()];
int oldSortedIndex = 0;
for(IndexedTreeIterator i = previousSorted.iterator(0); i.hasNext(); oldSortedIndex++) {
IndexedTreeNode oldSortedNode = i.next();
IndexedTreeNode unsortedNode = (IndexedTreeNode)oldSortedNode.getValue();
IndexedTreeNode newSortedNode = (IndexedTreeNode)unsortedNode.getValue();
int newSortedIndex = newSortedNode.getIndex();
reorderMap[newSortedIndex] = oldSortedIndex;