简体   繁体   中英

Java Comparator for comparing instances of a generic class

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?

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> 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 Comparable s are consumers, as they consume types that they are comparing, we use ? super T1 ? super T1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM