OK, I have been thinking some more, and have a few options to choose between:
1. Create a new Collection class, keep an internal List and make sure all adds happens at the appropriate index2. Create a new Iterable class and keep an internal TreeSet<List><T>>3. Create a new Comparator class that only returns 0 when the elements really are equal according to equals(), then use this comparator together with a TreeSet
Option 3 was my first thought, since In my mind that should be quite easy. But it turned out that it was in fact not so easy. What I am trying to sort are objects that implement the interface org.springframework.core.Ordered. There is already a Comparator for Ordered-objects, however if the order number of both objects are the same then the comparator simply returns 0. But I only want it to return 0 if the objects really are equal each other. Because there will be Ordered objects that are far from equal, but with the same order number. If the comparator returns 0 then the TreeSet regards these objects to be equal.
The problem I'm having is to decide if element e1 should be considered less then or greater then element e2 when e1.getOrder() == e2.getOrder(). What I have done now, in a
test implementation, is:
A: If e1.equals(e2) return 0B: Otherwise, if compare(e1.getValue(), e2.getValue()) is non-0, return itC: Otherwise, if e1 and e2 implements Comparable and c1.compareTo(e1) is non-0, return itD: Otherwise, do a compare of the hash codes, if non-0 then return itE: [We can assume that we get here quite rarely] Otherwise, compare hashcodes of the element class objects, if non-0 then return itF: Otherwise, we have any more ways of comparing the elements, so we return -1 just in order to return *something*, and not returning 0
I have no problem with the somewhat complex steps involved, since it will rarely go all the way down to E or F asuming good hashcode implementations. The problem I have is with last step, F. Because it breaks the contract of Comparable. If a compare(e1, e2) comes down to F, then the result is -1, but the result of compare(e2, e1) is *also* -1! Even if this will hardly ever happen, it *can* happen.
What do you guys think about this Comparator? It felt "just wrong" when I wrote it, but I also don't like the way that org.springframework.core.OrderComparator is written since it can consider non-equal objects (as by o1.equals(o2)) to be equal (by returning 0). Or, when I think about it, my *real* pet peve is the Set interface, that clearly states that it regards objects as equal if the compare/compareTo results in 0. What it should do, if you ask me, is to do a subsequent call o1.equals(o2) and only consider them as duplicates if it returns true.
But since the Set-implementations aren't gonna change any time soon (or not at all) in this regard, I'm starting to lean to option 2 above since it is simpler then option 1 and cleaner then option 3.
/Jimi