Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparator for comparing instances of a generic class

Tags:

java

generics

I have the following comparator class:

public class CustomTupleComparator implements Comparator<Tuple>
{
    public int compare(Tuple o1, Tuple o2)
    {
        int result = o1.getSecond().compareTo(o2.getSecond());

        return result != 0
               ? result
               : - o1.getFirst().compareTo(o2.getFirst());
    }
}

The Tuple class itself is generic with two type parameters:

public class Tuple<T1 extends Comparable, T2 extends Comparable>
{...}

Why am I getting unchecked call warnings about the compareTo() methods?

like image 647
Zoltan Magyar Avatar asked Nov 22 '13 13:11

Zoltan Magyar


1 Answers

Why am I getting unchecked call warnings about the compareTo() methods?

Because you are using raw type Tuple, instead of parameterized type. To use a parameterized type Tuple however, you would need to make the CustomTupleComparator class generic itself:

public class CustomTupleComparator<T1 extends Comparable<? super T1>, 
                                   T2 extends Comparable<? super T2>> 
             implements Comparator<Tuple<T1, T2>>
{
    @Override
    public int compare(Tuple<T1, T2> o1, Tuple<T1, T2> o2)
    {
        int result = o1.getSecond().compareTo(o2.getSecond());

        return result != 0 ? result
                           : -o1.getFirst().compareTo(o2.getFirst());
    }
}

Also, you should change your Tuple class, to make the type parameters use generic Comparable, and not raw type:

public class Tuple<T1 extends Comparable<? super T1>, 
                   T2 extends Comparable<? super T2>> { }

Note: I've used Comparable<? super T1> instead of Comparable<T1> so as to make it work for subtypes too, where the super types are implementing Comparable<SuperType>.

Also, since Comparables are consumers, as they consume types that they are comparing, we use ? super T1.

like image 140
Rohit Jain Avatar answered Sep 30 '22 02:09

Rohit Jain