让你自己的班级'可比'

Bog*_* M. 5 java comparable

我也跟着教程,但未能使我Country的类ComparableBST.

主要:

BinarySearchTree A = new BinarySearchTree();
Country a = new Country("Romania", "Bucharest", 1112);
A.insert(a);
Run Code Online (Sandbox Code Playgroud)

国家级:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

@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
Run Code Online (Sandbox Code Playgroud)

名称冲突:类型为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
Run Code Online (Sandbox Code Playgroud)

和班级:

public class Country implements Comparable<Country>{
    private String name;
    private String capital;
    private int area;

Description Resource    Path    Location    Type
Run Code Online (Sandbox Code Playgroud)

类型Country必须实现继承的抽象方法Comparable.compareTo(Country)Country.java/Lab2_prob 4/src line 2 Java问题

And*_*nek 19

你的Country班级应该实施Comparable:

public class Country implements Comparable<Country>
Run Code Online (Sandbox Code Playgroud)

那你的compareTo方法应该是这样的:

@Override
public int compareTo(Country anotherCountry) {
    return anotherCountry.getName().compareTo(this.name);
}
Run Code Online (Sandbox Code Playgroud)

注意签名compareTo.参数可以(并且必须)Country不是类型Object.这是因为泛型类型参数on Comparable.好处是你不必再检查类型了.缺点是你只能与Country其他Country对象(或它的子类型)进行比较,但在大多数情况下,无论如何这都是你想要的.如果不是,则必须更改类型参数.例如,如果您使用Comparable<Object>签名compareTo可以Object再次.如果您愿意,可以在这里阅读泛型.


DNA*_*DNA 5

a Comparable应该返回:

一个负整数,零或正整数,因为此对象小于,等于或大于指定的对象.

但是,您的代码只返回-1或0,这是不正确的; 这意味着它this可以小于另一个对象,或者相等,但不是更大!

无需修改返回的值name.compareTo()- 您可以直接返回它们.