[英]I don't understand why my “Comparable” interface isn't working
I am trying to implement comparable
in order to use the Arrays.sort(array)
but for some reason its not finding the compareTo
method in the super class. 我试图实现
comparable
以便使用Arrays.sort(array)
但是由于某种原因,它没有在超类中找到compareTo
方法。 I am trying to compare strings FYI. 我正在尝试比较字符串仅供参考。
Edit: Sorry I forgot to add the error I am getting. 编辑:对不起,我忘了添加我得到的错误。 Here it is:
这里是:
Employee.java:32: error: cannot find symbol
return super.compareTo((Object)other);
^
symbol: method compareTo(Object)
Code: 码:
public abstract class Employee implements Cloneable, Comparable
{
private Name name;
private double weeklyPay;
public Employee(String first, String middle, String last, double weeklyPay)
{
this.weeklyPay = weeklyPay;
name = new Name(first,middle,last);
}
public Employee(String last, double weeklyPay)
{
this.name = name;
this.weeklyPay = weeklyPay;
name = new Name(last);
}
public Employee(String first, String last, double weeklyPay)
{
this.name = name;
this.weeklyPay = weeklyPay;
name = new Name(first,last);
}
public abstract double getWeeklyPay();
public String getFullName()
{
return name.getFullName();
}
public int compareTo(Object other)
{
return super.compareTo((Object)other);
}
public int compareTo(Name name)
{
return compareTo((Object)name.getFullName());
}
java.lang.Object
, which is your superclass, does not implement Comparable
. 作为您的超类的
java.lang.Object
没有实现Comparable
。 You should change the signature of your class to: 您应该将班级的签名更改为:
public abstract class Employee implements Cloneable, Comparable<Employee>
And then implement this method: 然后实现此方法:
public int compareTo(Employee other) {
// logic to compare here
}
With actual logic to do the comparison (aka, don't try and depend on some other objects implementation). 使用实际的逻辑进行比较(也就是,不要尝试依赖其他一些对象的实现)。
Comparable
is an interface
, and it therefore has no default implementation. Comparable
是一个interface
,因此没有默认实现。 Your class does not extend any other class
, which means that it is not inheriting any implementation(s) either. 您的类不会扩展任何其他
class
,这意味着它也不会继承任何实现。
super.compareTo(...)
will always fail in this way as a result, unless you extend another class that provides an implementation. 因此,除非您扩展另一个提供实现的类,否则
super.compareTo(...)
总是会以这种方式失败。
我认为您确实想编写不同的比较器,每个要比较的字段之一:名称,等等。
The problem is you are attempting to call super.compareTo( Object object)
but because your class Employee does not itself extend a class, it will be looking for the compareTo method in Object and Object does not have that method. 问题是您试图调用
super.compareTo( Object object)
但是由于您的Employee类本身没有扩展一个类,因此它将在Object中查找compareTo方法,而Object没有该方法。 You need to actually implement the compareTo functionality within Employee. 您实际上需要在Employee中实现compareTo功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.