java - 两个类之间的compareTo()方法设置

标签 java

我正在尝试在我的一个类上实现 compareTo() 方法,但在实现该方法的“步骤”方面遇到了麻烦,只需要解释一下我做错了什么。

我想使用 compareTo() 方法来比较地点和特定事物的地点

我收到错误:
compareTo(Venue) 方法对于 Venue 类型未定义
compareTo() 方法的第一行。

我认为发生这种情况是因为我没有从 Place 类 正确继承 Place(String name),我认为需要能够实际比较 2地方。

我不确定这是如何完成的,对正在发生/应该发生的事情的解释将进一步澄清

1 级:

public class Place {
    // the name of the place
    private String name;
    // invariant: name != null 

    // Creates a new place with the given name.
    public Place(String name){
    if (name != null){
        this.name = name;   
    } else 
        throw new NullPointerException();
    }

    //returns the name of a place
    public String getName(){
        return name;
    }
}

2 级:

public class Thing implements Comparable<Thing>{
    // the name of the place at which the thing occurs
    private Place place;

    // Creates a new thing for the given place
     public Thing(Place place) {
        if (place == null){
            throw new NullPointerException("Place cannot be null");
        }
        this.place = place;
    }

    // Returns the place of the thing.
    public Place getPlace() {
        return place;
    }

    public int compareTo(Thing thing) {
        if (getPlace().compareTo(thing.getPlace()) > 0){
            return 1;

        } else if //..rest of compareTo method  
        }
    }
}

请原谅措辞不佳,因为我发现很难将我的思维过程转化为具有“java意义”的句子

最佳答案

如果您想在 Thing 类中使用 Place 类,则需要一个compareTo() 方法。

public class Place implements Comparable<Place> {
// the name of the place
private String name;
// invariant: name != null 

// Creates a new place with the given name.
public Place(String name){
if (name != null){
    this.name = name;   
} else 
    throw new NullPointerException();
}

//returns the name of a place
public String getName(){
    return name;
}

public int compareTo(Place other) {
    // do something here
}

}

在您的代码中,编译器不知道当您调用 getPlace().compareTo(...) 时要做什么,因为该方法尚未在 Place 类中定义,而 getPlace () 返回。

关于java - 两个类之间的compareTo()方法设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29668263/

相关文章:

java - 对字符串数组进行排序

JAVA创建Json数组不带引号

java - 是否有用于从 Android(Java) 类生成 UML 的好插件?

Java - 启动时读出系统环境

用于跨平台的 Java GUI

java - javafx 中使用 TableView 进行多重过滤

java.lang.NoClassDefFoundError : Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup 错误

java - 如何使用princeXML自动拆分表

java - 如何使用主机名 validator ?

java - Eclipse + Tomcat 7 + Audit Trial DataSource - 服务器启动失败