Java comparable的CompareTo不接受对象类型以外的参数。

Java comparable的CompareTo不接受对象类型以外的参数。,java,comparator,comparable,Java,Comparator,Comparable,奇怪的是,这并不像我预期的那样有效。我编写了一个简单的java类,它实现了Comparable接口并重写compareTo()方法。但是,它不允许我传递对象以外的特定类型的参数。我在网上查看了其他人的代码,他们确实使用了其他类型的对象,我将他们的代码复制到eclipse中,但仍然得到了相同的错误 我的问题是,;我要做的是将这个对象与类型的对象进行比较,比如说Person。我对Comparator接口(compare()方法)也有同样的问题 这是我在网上找到的代码 public class Per

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

我的问题是,;我要做的是将这个对象与类型的对象进行比较,比如说Person。我对Comparator接口(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!");
    }
}
}


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

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

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

public class Person implements Comparable {

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

public class Person implements Comparable {
public class Person implements Comparable<Person> {
@Override
public int compareTo(Person personToCompare){