gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:15:59 25 4
gpt4 key购买 nike

我正在尝试在我的一个类上实现 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com