Gytis: why can't we use just <T extends Comparable<T>> <T extends Comparable<T>> almost, but not entirely does the job. It is best explained with an example, such as GregorianCalendar from before. If you insert GregorianCalendar instead of T, you get
<GregorianCalendar extends Comparable<GregorianCalendar>>
which is not true! Therefore, a list of GregorianCalendars could not be used as input to doit if we just used <T extends Comparable<T>>.
GregorianCalendar does implement Comparable<Calendar>,
but it does
not implement Comparable<GregorianCalendar>!
I admit this is not very intuitive, but it's the way generics work in general, and it is the reason wildcards were introduced.
I have an idea of how to extend the language so that we won't necessarily have to write <T extends Comparable<? super T>> every single time, but that's another I discussion I may post somewhere else if I suddenly have oodles of time.
Gytis: your solution is restricted to Comparable types only, but some operations like EQUALS or IS_NULL does not need Comparable arguments at all True, and I didn't even think about that. It just makes your question even better
. I'm not sure there
is any super elegant solution to this problem. If your client does this...
then the original code you posted (with the cast) will throw a ClassCastException if myOp == MORE because Number does not implement Comparable! This is
exactly the reason the compiler emits an unchecked warning with JDK1.5: In some situations, the code will fail.
If you know for sure that no client is going to do something like that, and you just want to cast without triggering a warning (perhaps this is what you asked for from the very beginning?), I am going to have to owe you a reply, since I didn't dig into it any deeper and don't have too much time right now. Try searching for @SuppressWarnings("unchecked"), it might give you a solution, although not the elegant one you were hoping for. I think (hope) there is be a better solution.
Please let me know if you make any more experiences in this matter, as I find it very interesting: Perhaps generics didn't entirely get rid of the need for casting anyway! I will also look into it some more later, but for the moment, my lunch break is over :-)