我的类(class)详细介绍了市中心餐馆的属性,所述属性是 x/y 位置和排名。问题是,每当我运行该程序时,它都会抛出一个错误,指出非抽象类“Downtown”不会覆盖抽象方法“compareTo”。我无法使此类抽象,因为我需要在该代码块之外初始化对象。我的程序哪里出了问题?我的compareTo实现有问题吗?任何建议将不胜感激。
public class Downtown implements Comparable<Downtown> {//Throws error on this line
private int x;
private int y;
private int rank;
public Downtown(int x, int y, int rank) {
this.x = x;
this.y = y;
this.rank = rank;
}
//Appropriate setters and getters for x , y and rank
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int compareTo(Downtown p1, Downtown p2)//Actual comparison
{
// This is so that the sort goes x first, y second and rank last
// First by x- stop if this gives a result.
int xResult = Integer.compare(p1.getX(),p1.getX());
if (xResult != 0)
{
return xResult;
}
// Next by y
int yResult = Integer.compare(p1.getY(),p2.getY());
if (yResult != 0)
{
return yResult;
}
// Finally by rank
return Integer.compare(p1.getRank(),p2.getRank());
}
@Override
public String toString() {
return "["+x+' '+y+' '+rank+' '+"]";
}
最佳答案
Java 的 Comparable<T>
接口(interface)定义compareTo
方法如下:
int compareTo(T o);
这意味着该方法必须采用一个参数;另一个参数是对象本身,即 this
。您需要实现这个单参数方法来代替双参数方法来解决此问题。
编译器将通过使用 @Override
annotation 帮助您解决此类问题根据你的方法:
@Override // Issues an error
public int compareTo(Downtown p1, Downtown p2)
@Override // Compiles fine
public int compareTo(Downtown other)
关于java - 我的类没有重写抽象方法compareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687466/