【问题标题】:CompareTo of comparable does not take arguments other than Object type.可比较的 CompareTo 不接受 Object 类型以外的参数。
【发布时间】:2016-01-05 13:21:58
【问题描述】:

这似乎很奇怪,这不像我预期的那样工作。我编写了一个实现 Comparable 接口并覆盖 compareTo() 方法的简单 java 类。但是,它不允许我传递除 Object 之外的特定类型的参数。我在网上查看了其他人的代码,他们确实使用了其他类型的对象,然后我将他们的代码复制到了 eclipse 中,但仍然出现同样的错误。

我的问题是;我必须做些什么才能将此对象与类型对象进行比较,比如说Person。我对比较器接口(compare() 方法)也有同样的问题。

这段代码是我在网上找到的。

public class Person implements Comparable {

private String name;
private int age;

public Person(String name, int age) {
    this.name = name;
    this.age = age;
}

public int getAge() {
    return this.age;
}

public String getName() {
    return this.name;
}

@Override
public String toString() {
    return "";
}

@Override
public int compareTo(Person per) {
    if(this.age == per.age)
        return 0;
    else
        return this.age > per.age ? 1 : -1;
}

public static void main(String[] args) {
    Person e1 = new Person("Adam", 45);
    Person e2 = new Person("Steve", 60);

    int retval = e1.compareTo(e2);
    switch(retval) {
        case -1: {
            System.out.println("The " + e2.getName() + " is older!");
            break;
        }
        case 1: {
            System.out.println("The " + e1.getName() + " is older!");
            break;
        }
        default:
            System.out.println("The two persons are of the same age!");
    }
}

}

【问题讨论】:

    标签: java comparator comparable


    【解决方案1】:

    您需要使用泛型来提供特定类型。

    public class Person implements Comparable<Person> { // Note the generic to Person here.
        public int compareTo(Person o) {}
    }
    

    Comparable 接口是这样定义的,

    public interface Comparable<T> {
        public int compareTo(T o);
    }
    

    【讨论】:

      【解决方案2】:

      您可以利用泛型来使用自定义对象类型。从

      更改您的类定义
      public class Person implements Comparable {
      

      public class Person implements Comparable<Person> {
      

      现在您应该能够将 Person 对象传递给您的 compareTo 方法,如下所述:

      @Override
      public int compareTo(Person personToCompare){
      

      在此处了解有关泛型的更多信息:

      https://docs.oracle.com/javase/tutorial/java/generics/types.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多