简体   繁体   English

可比和比较

[英]Comparable and compareto

I have a problem. 我有个问题。 I have a class that extends another class and implements Comparable. 我有一个扩展了另一个类并实现Comparable的类。 But when I tried to compile my program I had this error: Flight is not abstract and does not override abstract method compareTo. 但是,当我尝试编译程序时,出现了以下错误:Flight不是抽象的,并且不覆盖抽象方法compareTo。 Anyway, the code of Flight is this: 无论如何,飞行代码是这样的:

class Flight extends KeyFlight implements Comparable<Flight>{

 public KeyFlight kf;
 public boolean departure;

 public void Flight(){
 KeyFlight kf=new KeyFlight();
 boolean departure=false;
 }

 public int compareTo(KeyFlight other){
  if (kf.time==other.time){
  if (kf.key<other.key){
   return kf.key;
  } else {
   return other.key;
  } 
 } else {
  if (kf.time <other.time){
   return kf.key;
  } else {
   return other.key;
  }  
 }
}
}

Thank you in advance! 先感谢您!

You should use 你应该用

implements Comparable<KeyFlight>

Instead of 代替

implements Comparable<Flight>

As you want to compare two keyflights rather than flights itself. 正如您要比较两个关键时刻而不是航班本身。 The Type of parameter that you defines in compareTo, should match with the type you specified in implements clause that you are going to compare with. 您在compareTo中定义的参数的Type应该与您要与之比较的Implements子句中指定的类型相匹配。

Another issue with your code is, in your constructor you are re-defining KeyFlight, it should be 代码的另一个问题是,在构造函数中,您正在重新定义KeyFlight,它应该是

public void Flight(){
    kf=new KeyFlight();

Else you will get NullPointerException in future. 否则,您将来会收到NullPointerException。 Same applies for your departure boolean. 同样适用于您的出发布尔值。

A side note, By Default in java boolean is initialised to false, so you don't have to explicitly say that in constructor. 附带说明一下,默认情况下,java boolean中的Default初始化为false,因此您不必在构造函数中明确声明。

我认为compareTo的参数类型是错误的,应该是

public int compareTo(Flight other){

The compareTo method in your class is not to a valid override because you define that your class implement Comparable<Flight> So in order to override this method in your class you need to change the variable type of other from KeyFlight to Flight . 您的类中的compareTo方法无效,因为您定义了类实现Comparable<Flight>因此,要在您的类中覆盖此方法,您需要将其他变量的类型从KeyFlightFlight

 @Override
 public int compareTo(Flight o) {
  //your logic here
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM