【问题标题】:Making your own class 'Comparable'让自己的班级“可比”
【发布时间】:2012-10-24 14:42:00
【问题描述】:

我遵循了一个教程,但未能为我的BST 制作我的Country 类Comparable。

主要:

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 line 2 Java Problem

【问题讨论】:

  • 您的Country 课程是否扩展Comparable&lt;Country&gt;?
  • 您实际上遇到了什么问题或错误?

标签: java comparable


【解决方案1】:

你的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&lt;Object&gt;,compareTo 的签名可以再次为Object。你可以阅读更多关于泛型的信息here。

【讨论】:

  • 刚刚记得Comparable是一个接口。很抱歉这个错误。
  • 你能检查一下我在你建议我的修复后得到的错误吗?请漂亮
  • @mic 你是对的,我的错。我会编辑它。谢谢!
【解决方案2】:

Comparable 应该返回:

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

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

name.compareTo()返回的值无需修改,直接返回即可。

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    相关资源
    最近更新 更多