使自己的班级“可比” [英] Making your own class 'Comparable'
问题描述
我遵循了教程,但未能为我的设置
。 Country
类可比较
BST
I followed a tutorial, but failed to make my Country
class Comparable
for my BST
.
Main:
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
名称冲突:compareTo(Object )类型Country的擦除与类型Comparable的compareTo(T)相同,但是不会覆盖它Country.java / Lab2_prob 4 / src第17行Java问题
Name clash: The method compareTo(Object) of type Country has the same erasure as compareTo(T) of type Comparable but does not override it Country.java /Lab2_prob 4/src line 17 Java Problem
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问题
The type Country must implement the inherited abstract method Comparable.compareTo(Country) Country.java /Lab2_prob 4/src line 2 Java Problem
推荐答案
您的 Country
类应实现 Comparable
:
public class Country implements Comparable<Country>
然后,您的 compareTo
方法应如下所示:
Then your compareTo
method should look like this:
@Override
public int compareTo(Country anotherCountry) {
return anotherCountry.getName().compareTo(this.name);
}
请注意 compareTo $ c $的签名c>。该参数可以(并且必须)是
Country
类型,而不是 Object
类型。这是必需的,因为 Comparable
上的通用类型参数。好处是您不必再检查类型。缺点是您只能将 Country
与其他 Country
对象(或其子类型)进行比较,但是在大多数情况下,这是反正你想要什么。如果不是,则必须更改type参数,例如如果使用 Comparable< Object>
,则 compareTo
的签名可以是 Object
。您可以在此处阅读更多信息。
Note the signature of compareTo
. The parameter can (and must) be of type Country
, not Object
. This is required because of the generic type parameter on Comparable
. The upside is you don't have to check the type anymore. The downside is you can only compare Country
to other Country
objects (or its subtypes), but in most cases this is what you want anyway. If not you have to change the type parameter, e.g. if you use Comparable<Object>
the signature of compareTo
can be Object
again. You can read more about generics here.
这篇关于使自己的班级“可比”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!