You ask different questions in the question title and in the question body.
You weren't clear on why the exception-capable function used by the compare()
method would throw an exception. It's either because there are certain uncomparable objects in the collection (like a NaN
numberic value) or else it's because there are certain pairs of objects that can't compared against each other.
Why can't I throw an exception in the Comparator?
I would guess Comparator.compare()
isn't designed to throw a checked exception because:
it is assumed that any items that you would wish to compare/sort would always be comparable.
if a Comparator.compare()
could throw some sort of expected (i.e. checked) exception, then I can envision a couple of undesirable scenarios:
a. a sort could abort because there is some sort of uncomparable object in there - the likely response being to remove the uncomparable object(s) and try the sort again
b. multiple sorts on the different orderings of the same collection of objects could sometimes abort with an exception and sometimes succeed depending on whether or not a pair uncomparable objects happened to come up for comparison during the sort
This is of course just my conjecture.
How would I solve this?
I going to assume that the reason the exception-possible function that your Comparator.compare()
uses throws an exception is because there's an uncomparable object in the collection (like a NaN
numberic value). Options include:
Sort a copy of the list with the uncomparable object(s) removed.
Throw an unchecked (runtime) exception to abort the sort. Not sure what you would do then other than #1 above.
Follow the NaN
approach and make it so those objects come out at beginning or end.
NaN
values are normally uncomparable to other values, but during a sort, the comparator defines its own total ordering so that NaN
values end up at the end of the sorted collection.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html#sort(double[])
... The < relation does not provide a total order on all floating-point values; ... a NaN value compares neither less than, greater than, nor equal to any floating-point value, even itself.
... To allow the sort to proceed, ... this method uses the total order imposed by Double.compareTo(java.lang.Double).
... This ordering differs from the < relation in that ... NaN is considered greater than any other floating-point value. For the purposes of sorting, all NaN values are considered equivalent and equal.
To do this, code your Comparator.compare()
such that any incomparable object always compares greater than any comparable object and it always compares equal to any other incomparable object.