Suppose the following generic class with 2 types T, U
public class Pair<T, U> implements Comparable<T, U> { //Error 1
private final T first;
private final U second;
public Pair(T first_, U second_) {
first = first_;
second = second_;}
public T getFirst() { return first; }
public U getSecond() { return second; }
}
and the list of its items
List<Pair<Integer, Integer>> = new ArrayList<>()
that need to be sorted according to the first/second attribute. Unfortunately, the class definition contains some issue, the following error appears:
Error 1: wrong number of type arguments
How to design the comparator class? This code is probably completely wrong
public class SortBySecond implements Comparable <Pair <T, U>> {
public int compare(final Pair<T, U> p1, final Pair<T, U> p2) //Error 2
{
return t1.getSecond().compareTo(t2.getSecond()); //Updated comparator
}
}
Error 2 : Can not find symbols T, U, V
Thanks for your help.
<and>, those only work for primitive types. Instead try something likereturn p1.getSecond().compareTo(p2.getSecond());.Pairclass implementComparable. Who knows ifTorUare comparable? Leave it up to the user to create a customComparatorif they want to sort their pairs, that way they can decide whether to sort by the first field, the second, combine them, or whatever.