Comparator and "Equalator"
Hello.
I was browsing through the Java docs online for information about TreeSet. And I came across the following:
"Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals."
So, to avoid any 'trouble', one should make sure that the Comparator<T>.compare( T a,b) returns 0 whenever a.equals(b) is true.
Now, TreeSet() allows us to pass a Comparator in it's ctor(). Why doesn't it allow us to also pass in a 'Equaltor" in the constructor aswell? What if I had a set of Songs with fields for title, album, band, and year, and now I want to change the criteria for order and uniqueness in a set from any one of the Songs' fields?
So I have a collectoin of Songs from my iTunes library. I want to make a set of titles, albums, and bands
According to the quote above, I can't do it cleanly, because I would have to change equals() in each case in order to avoid the collection from acting "strangely". It seems like we should be able to pass an Equal-Object just like Comparator.
Am I missing something? Thanks.
Re: Comparator and "Equalator"
I think what you may be missing is that something like TreeSet or TreeMap is sorted *online*, so any sorting it does happens whenever you modify it (add or remove objects). What you're looking for is something that is sorted 'offline' or on demand, or externally. A list is an 'ordered collection' - one class that does offer to sort Lists on a specified Comparator is java.util.Collections - see the sort(List, Comparator) method.