San*_*ran 2 java sorting compareto comparable
我目前在理解Comparable 类的compareTo 方法如何工作以及如何重写它方面遇到一些困难。我有成对的数组,每个对都包含 2 个双精度值,我正在尝试对其进行排序。这是我尝试过的:
static class Pair implements Comparable<Pair>
{
double x;
double y;
Pair(double x, double y)
{
this.x = x;
this.y = y;
}
public double compareTo(Pair other)
{
return y - other.y;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它无法编译,而是给我这个错误:
Main.java:5: error: Pair is not abstract and does not override abstract method compareTo(Pair) in Comparable
static class Pair implements Comparable<Pair>
^
Main.java:14: error: compareTo(Pair) in Pair cannot implement compareTo(T) in Comparable
public double compareTo(Pair other)
^
return type double is not compatible with int
where T is a type-variable:
T extends Object declared in interface Comparable
2 errors
Run Code Online (Sandbox Code Playgroud)
它在使用整数时有效,但在使用双精度数时不起作用,为什么呢?我怎样才能让它与双打一起工作?谢谢。
这可以推广到下面的实现,以与任何 T,V 实现Comparable接口的 Pair 一起使用。比较不可比较的类的对象通常是没有意义的(在完美的世界中!)。
public class GenComparableStackOverflow {
public static void main(String[] args){
Pair<Double,Double> pair1 = new Pair<>(2.0,2.0);
Pair<Double,Double> pair2 = new Pair<>(4.0,1.0);
Stream.of(pair1,pair2).sorted().forEach(System.out::println); //Uses compareTo
}
}
class Pair<T extends Comparable<T>,V extends Comparable<V>> implements Comparable<Pair<T,V>> {
T x;
V y;
Pair(T x, V y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Pair{" +
"x=" + x +
", y=" + y +
'}';
}
@Override
public int compareTo(Pair<T, V> o) {
return this.y.compareTo(o.y);
}
}
Run Code Online (Sandbox Code Playgroud)
这比您的自定义实现更好,因为这些类Comparable已经重写了compareTo()方法。对于您的情况,这将在您不知情的情况下使用 Double.compareTo() :)