我正在学习Java并做一些简单的编程问题。其中之一是在Octagon类中实现Comparable接口,以允许根据边长度对八边形进行排名。以下是我的代码片段:
class Octagon implements Comparable
{
private double side;
public Octagon(double side)
{
this.side = side;
}
public double getSide()
{
return side;
}
@Override
public int compareTo(Octagon oct)
{
/*
if (this.getSide()==oct.getSide())
return 0;
return this.getSide()>oct.getSide()?1:-1;
*/
/*
if(this.getSide()==oct.getSide())
return 0;
else if (this.getSide()<oct.getSide())
return 1;
else
return -1;
*/
/*
if (this.getSide()>oct.getSide())
return 1;
else if (this.getSide() == oct.getSide())
return 0;
else
return -1;
*/
/*
if(this.getSide()<oct.getSide())
return -1;
else if (this.getSide() == oct.getSide())
return 0;
else
return -1;
*/
/*
if(this.getSide()<oct.getSide())
return -1;
else if (this.getSide()>oct.getSide())
return 1;
else
return 0;
*/
/*
if(this.getSide()>oct.getSide())
return 1;
else if (this.getSide()<oct.getSide())
return -1;
else
return 0;
*/
}
}
我已经尝试了所有可能的排列来比较双方,正如你在所有注释掉的区块中看到的那样,似乎编译器随机抱怨方法没有覆盖抽象compareTo(T o )有时比较的方法然后它突然没有其他时间。我真的不知道这里发生了什么。任何帮助表示赞赏。
答案 0 :(得分:2)
你需要这样:
class Octagon implements Comparable<Octagon>{//Generic allows compiler to have Octagon as param
@Override
public int compareTo(Octagon o) {
return 0;
}
}
或
class Octagon implements Comparable{//No generic used. Allows to compare any object(s)
@Override
public int compareTo(Object o) {
return 0;
}
}