Comparators.reverseOrder issues

Georgiy Rakov georgiy.rakov at oracle.com
Mon Oct 29 03:31:07 PDT 2012


Hello colleagues,
could you please give your thoughts and comments. Do you consider it 
worth taking into account?

Thanks, Georgiy.

On 24.10.2012 16:59, Georgiy Rakov wrote:
> 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.
>
>


More information about the lambda-dev mailing list