我遵循了教程,但是没有为我的Country
创建我的Comparable
类BST
。
主要:
BinarySearchTree A = new BinarySearchTree();
Country a = new Country("Romania", "Bucharest", 1112);
A.insert(a);
国家类别:
public int compareTo(Object anotherCountry) throws ClassCastException {
if (!(anotherCountry instanceof Country))
throw new ClassCastException("A Country object expected.");
String anotherCountryName = ((Country) anotherCountry).getName();
int i = this.name.compareTo(anotherCountryName);
if(i < 0){
return -1;
} else {
return 0;
}
}
错误:
@Override
public int compareTo(Object anotherCountry) throws ClassCastException {
if (!(anotherCountry instanceof Country))
throw new ClassCastException("A Country object expected.");
String anotherCountryName = ((Country) anotherCountry).getName();
return this.name.compareTo(anotherCountryName);
Description Resource Path Location Type
名称冲突:Country类型的compareTo(Object)方法与Comparable类型的compareTo(T)具有相同的擦除,但不会覆盖Country.java / Lab2_prob 4 / src第17行Java问题
Description Resource Path Location Type
The method compareTo(Object) of type Country must override or implement a supertype method Country.java /Lab2_prob 4/src line 17 Java Problem
和班级:
public class Country implements Comparable<Country>{
private String name;
private String capital;
private int area;
Description Resource Path Location Type
Country类型必须实现继承的抽象方法Comparable.compareTo(Country)Country.java / Lab2_prob 4 / src第2行Java问题
您的Country
类应实现Comparable
:
public class Country implements Comparable<Country>
然后您的compareTo
方法应如下所示:
@Override
public int compareTo(Country anotherCountry) {
return anotherCountry.getName().compareTo(this.name);
}
注意compareTo
的签名。该参数可以(并且必须)是Country
类型,而不是Object
类型。这是必需的,因为Comparable
上具有通用类型参数。好处是您不必再检查类型。缺点是您只能将Country
与其他Country
对象(或其子类型)进行比较,但是在大多数情况下,这都是您想要的。如果不是,则必须更改type参数,例如如果使用Comparable<Object>
,则compareTo
的签名可以再次为Object
。您可以阅读有关泛型here的更多信息。
Comparable应该返回:
负整数,零或正整数,因为此对象较小大于,等于或大于指定的对象。
但是,您的代码仅返回-1或0,这是不正确的;这意味着this
可以小于另一个对象,或者等于,但是不能大于!
无需修改name.compareTo()
返回的值-您可以直接将其返回。