我正在尝试在我的一个类中实现compareTo()
方法,但在到达该步骤的“步骤”时遇到了麻烦,只需要对我在做什么做的一个解释即可。
我想使用compareTo()
方法比较一个地方和一个特定事物的地方。
我收到错误消息:
在compareTo()
方法的第一行中,对于Venue类型,未定义compareTo(Venue)方法。
我认为这是因为我没有正确地从Place(String name)
继承Place class
,我认为需要能够真正比较两个地方。
我不确定如何完成此操作,对/应该进行的解释将进一步阐明
第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有意义”的句子中
最佳答案
如果要在Place
类中使用它,则Thing
类需要一个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()返回此方法。