I believe that all this is due to the intention of turning the ReverseComparator into a singlenton object. Since a singlenton instance must be defined in a static context, it makes no sense to use any generic types.
static final ReverseComparator REVERSE_ORDER = new ReverseComparator();
This code generates a raw warning.
Thus, the implementation of ReverseComparator, which is used only for this, could be what you proposed or how it was implemented. Perhaps they chose the current implementation because it is easier to read, and because they thought that further generalization is not required if it is only private use for this simple purpose.
Running the Java decompiler on your implementation and on the Oracle implementation creates the same byte codes of the source type.
public int compare(java.lang.Comparable, java.lang.Comparable public int compare(java.lang.Object, java.lang.Object);
In the end, when the comparator is displayed through the public interface of the Collections class in the reverseOrder()
method, casting and an unchecked warning cannot be avoided. But we are all sure that this cannot fail, regardless of the types used.
Bottom line, IMHO I think that the only reason it was implemented is due to the clarity of the code or the desire not to complicate things more than necessary if, in any case, an uncontrolled warning cannot be prevented. But hey, this is not the first time I am mistaken; -)
source share