我遵循了一个教程,但未能使我的Country类成为我的BST的Comparable。
Main:
BinarySearchTree A = new BinarySearchTree();
Country a = new Country("Romania", "Bucharest", 1112);
A.insert(a);Country类:
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和class:
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 line 2 Java Problem
发布于 2012-10-24 22:50:18
您的Country类应该实现Comparable
public class Country implements Comparable<Country>那么你的compareTo方法应该是这样的:
@Override
public int compareTo(Country anotherCountry) {
return this.name.compareTo(anotherCountry.getName());
}注意compareTo的签名。参数可以(且必须)是Country类型,而不是Object类型。这是必需的,因为Comparable上的泛型类型参数。好处是你不再需要检查类型了。缺点是您只能将Country与其他Country对象(或其子类型)进行比较,但在大多数情况下,这正是您想要的。如果不是,则必须更改类型参数,例如,如果使用Comparable<Object>,则compareTo的签名可能再次为Object。您可以阅读有关泛型here的更多信息。
发布于 2012-10-24 22:47:57
Comparable应返回:
为负整数、零或正整数,因为此对象小于、等于或大于指定的对象。
但是,您的代码只返回-1或0,这是不正确的;这意味着this可以小于或等于其他对象,但不能大于它!
不需要修改name.compareTo()返回的值-您可以直接返回它们。
https://stackoverflow.com/questions/13051568
复制相似问题