views:

88

answers:

3

Let's say I have a collection of objects which can be sorted using a number of different comparators based on the different fields of the object. It would be nice to be able to know later on in the code which comparator was used to sort the Collection with and if it was ascending or descending. Is there anyway to do this elegantly instead of using a bunch of Booleans to keep track of things?

+1  A: 

No there's nothing with the implementations that does this. You would need to track it yourself. You could subclass a Collection implementation to add fields which hold this information.

You could also map the implementations to metadata as you like with a Map -- in particular it seems like you want IdentityHashMap to do this, since you don't want two different collections to be compared for equality as keys with equals().

I would store a boolean (ascending/descending), and a reference to the Comparator used to sort, if that's what completely determines the sort. Or if it's sorted on field, store a String naming the field perhaps.

Sean Owen
But, you also want the keys to be weak, so the map entries will drop off when the collection object gets collected. My vote is for Google Collections' weak-keyed concurrent map.
Chris Jester-Young
Great point, I agree.
Sean Owen
+2  A: 

Not for the Collection interface, but if you use a SortedSet there's a comparator() method where you can ask for its comparator.

Otherwise you'll have to subclass the collection class you're using to add the accessors you need.

Martin
I meant only one comparator at a time but could be any of those based on the different fields. Thanks.
Sanjay
A: 

sure:

define methods for your decorated Collection<Foo>

public List<Comparator<Foo>> getComparators() { ... }

and

public int whichComparator() { ... }

that returns which Comparator is currently in use from the List. You could make it fancier with a Map and some sensible keys (say, enums - perhaps even enums which implement the comparators) if you're modifying which comparators might be used over the life of the object, but I think the above is a good enough start.

Carl