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()));
}
}
Run Code Online (Sandbox Code Playgroud)
而且我有以下课程:
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 + ")";
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题:假设我有四个点p1,p2,p3,p3.如何使用Pair类将对(p1,p2)与(p2,p3)进行比较?我如何使用compareTo函数?谢谢
由于Point类未实现,因此无法使用此方法Comparable<Point>.你必须先解决这个问题.实际上,您应该将F和S限制为仅实现Comparable的类.
要约束F和S,请将类声明更改为:
public class Pair<F extends Comparable<F>, S extends Comparable<S>> implements Comparable<Pair<F,S>> {
Run Code Online (Sandbox Code Playgroud)
有了它,你不再需要投入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;
}
Run Code Online (Sandbox Code Playgroud)
在编写下面的代码时,编译器会告诉您Point必须实现的代码Comparable<Point>.
一旦你这样做,你可以:
Pair<Point, Point> pair1 = new Pair<>(p1, p2);
Pair<Point, Point> pair2 = new Pair<>(p3, p4);
int cmp = pair1.compareTo(pair2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |