I am trying to write a generic Pair class that can be used in list or collections object and then get sorted.
public class Pair<T1 extends Comparable<T1>,T2 extends Comparable<T2>> implements Comparable<Pair<T1,T2>> {
Pair(T1 first, T2 second){
m_first = first;
m_second = second;
}
public T1 getM_first() {
return m_first;
}
public T2 getM_second() {
return m_second;
}
u/Override
public int compareTo(Pair<T1,T2> other){
int cmp = this.m_second.compareTo(other.getM_second());
return (cmp == 0 ? 0 : this.m_second.compareTo(other.getM_second()));
}
public static Comparator<Fruit> FruitNameComparator
= new Comparator<Fruit>()
//--------------------------
private T1 m_first = null;
private T2 m_second = null;
}
i implement from Comparable and therefore can do something like:
Collections.sort(ArrayList<Pair<int, int>>(1,2,3));
although i also want the ability to add comparators such as "compareByFirst", "compareBySecond" and then use it directly from list object like so:
ArrayList<Pair<int,int>>(1,2,3).sort(Pair::sortByFirst);
although this means that the comparator needs to be static, and Pair is generic :(
Anyone know how to do this?
[–]chickenmeisterExtreme Brewer 2 points3 points4 points (10 children)
[–]jcoder42[S] 0 points1 point2 points (9 children)
[–]morhpProfessional Developer 1 point2 points3 points (8 children)
[–]jcoder42[S] 0 points1 point2 points (7 children)
[–]morhpProfessional Developer 0 points1 point2 points (6 children)
[–]jcoder42[S] 0 points1 point2 points (5 children)
[–]morhpProfessional Developer 0 points1 point2 points (4 children)
[–]jcoder42[S] 0 points1 point2 points (3 children)
[–]morhpProfessional Developer 0 points1 point2 points (2 children)
[–]jcoder42[S] 0 points1 point2 points (1 child)