gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:56:53 24 4
gpt4 key购买 nike

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: error: Human is not abstract and does not override abstract method compareTo(Human) in Comparable public class Human implements Comparable

这是怎么回事?请帮忙。

最佳答案

你想改变:

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);
}

关于java - Human 不是抽象的,不会覆盖抽象方法 compareTo(Human) .solution?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32790107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com