public class Pair<F,S> implements Comparable<Pair<F,S>> {
public F first;
public S second;
public F first() {
return first;
}
public void setFirst(F first) {
this.first=first;
}
public S second() {
return second;
}
public void setSecond(S second) {
this.second=second;
}
public Pair(F first, S second) {
super();
this.first=first;
this.second=second;
}
public int hashCode() {
return(first.hashCode()^second.hashCode());
}
@Override
public boolean equals(Object obj) {
return obj instanceof Pair && ((Pair)obj).first.equals(first) && (Pair)obj).second.equals(second);
}
public String toString() {
return first + " / " + second;
}
@SuppressWarnings("unchecked")
public int compareTo(Pair<F, S> o) throws ClassCastException{
int firstCompared = ((Comparable<F>) first).compareTo(o.first());
if(firstCompared!=0) return(firstCompared);
return(((Comparable<S>)second).compareTo(o.second()));
}
}
并且我有以下课程:
public class Point{
public int x;
public int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
public String toString(){
return "(" + x + "," + y + ")";
}
}
我的问题: 假设我有四个点p1,p2,p3,p3。如何使用Pair类将对(p1,p2)与(p2,p3)进行比较?我如何使用compareTo函数?谢谢
答案 0 :(得分:5)
由于您的Point类未实现Comparable<Point>
,因此无法使用此功能。你必须先解决这个问题。实际上,您应该将F和S限制为仅实现Comparable的类。
要约束F和S,请将类声明更改为:
public class Pair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<Pair<F,S>> {
这样,您就不再需要投射compareTo
:
@Override
public int compareTo(Pair<F, S> that) {
int cmp = this.first.compareTo(that.first);
if (cmp == 0)
cmp = this.second.compareTo(that.second);
return cmp;
}
编写下面的代码时,编译器会告诉您Point
必须实现Comparable<Point>
。
一旦你这样做,你可以:
Pair<Point, Point> pair1 = new Pair<>(p1, p2);
Pair<Point, Point> pair2 = new Pair<>(p3, p4);
int cmp = pair1.compareTo(pair2);