人类不是抽象的,不会覆盖抽象方法compareTo(Human).solution?

时间:2015-09-25 20:23:18

标签: java

public class Human implements Comparable<Human> {
    private int age;
    private String name;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String introduce() {
        return "Hey! I'm " + name + " and I'm " + age + " years old.";
    }

    public int CompareTo(Human h1, Human h2) {
            int hum1 = h1.getAge();
            int hum2 = h2.getAge();
            System.out.println(hum1 - hum2);
    }
}

此代码用于使用age参数对arraylist进行排序,并显示此错误信息

  

./ Human.java:6:错误:人类不是抽象的,也不会覆盖   抽象方法compareTo(Human)in Comparable public class Human   实现可比较

这里有什么问题?请帮助。

3 个答案:

答案 0 :(得分:4)

你想改变:

public int CompareTo(Human h1, Human h2)

为:

public int compareTo(Human h_other)

两件事:首先,“c”是小写的。其次,compareTo方法将this与另一个Human进行比较,因此它等同于(使用旧代码):

public int compareTo(Human h_other) {
    return CompareTo(this, other);
}

答案 1 :(得分:1)

您的compareTo方法签名错误。因此,编译器会告诉您未按指定实现Comparable接口。有关正确的方法签名,请参阅documentation

应该是这样的:

public int compareTo(Human other) {
    return Integer.compare(this.getAge(), other.getAge());
}

答案 2 :(得分:1)

在这里,您正在实现Comparable接口,

public int CompareTo( Human h1); 

来自Comparable接口的上述方法只能有一个参数。您正在使用两个参数实现它。这就是问题。