Comparators.reverseOrder issues

Georgiy Rakov georgiy.rakov at oracle.com
Wed Oct 24 05:59:56 PDT 2012


Hello,

there is a java.util.Comparators class in current API. It has two 
overload versions of method reverseOrder. A minor drawback in 
declaration and behavior seems to be there.

*1. static <T> Comparator<T> reverseOrder()*
The declaration seems to require some enhancement because following code 
throws ClassCastException though the code is considered as type safe:

    import java.util.Comparator;
    import java.util.Comparators;

    public class GenTest2 {
         static class MyObj {
         }
         public static void main(String arg []) {
             Comparator<MyObj> m = Comparators.reverseOrder();
             m.compare(new MyObj(), new MyObj());
         }
    }

For instance it could be enhanced like:

    public static <T extends Comparable<? super T>> Comparator<T>
    reverseOrder()

In which case the code above would simply fail to be compiled.

*2. public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)*
There is a reason to have the same enhancement here because following 
code throws ClassCastException as well:

    import java.util.Comparator;
    import java.util.Comparators;

    public class GenTest2 {
         static class MyObj {
         }
         public static void main(String arg []) {
             Comparator<MyObj> m2 = Comparators.reverseOrder(null);
             m2.compare(new MyObj(), new MyObj());
         }
    }

But on the other hand the enhancement is /definitely faulty /for this 
case because cmp could compare *any* objects in spite of whether it 
implements Comparable.
I could suppose that here it's possible either to sacrifice the type 
safety or to sacrifice the feature of returning natural order comparator.

The same goes for Collections.reverseOrder but I think it's impossible 
to modify there anything because of backward compatibility.

Source is attached for your convenient.

Thanks,
Georgiy.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: GenTest.java
Url: http://mail.openjdk.java.net/pipermail/lambda-dev/attachments/20121024/b84bdae7/GenTest-0001.java 


More information about the lambda-dev mailing list