【发布时间】:2021-04-25 06:24:53
【问题描述】:
我目前在理解 compareTo 方法如何用于 Comparable 类以及如何覆盖它时遇到了一些麻烦。我有成对的数组,每一个都包含 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;
}
}
但是,它没有编译,而是给了我这个错误:
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
它适用于整数,但不适用于双精度数,这是为什么呢?我怎样才能使它与双打一起工作?谢谢。
【问题讨论】:
-
compareToreturns anint,不是双重的。错误中也有说明。 -
不需要给
Pair<double,double>指定泛型参数吗? -
如何修改以使其适用于双打?
-
@JuanMendes 给定的类
Pair没有任何泛型类型参数;如果有,double将不是与它们一起使用的有效类型,因为它是原始类型。 -
@khelwood 我一定在想一个(不同的对)[docs.oracle.com/javase/9/docs/api/javafx/util/Pair.html]?我认为他们会自动装箱:p
标签: java sorting comparable compareto