实现 compareTo() 和 Comparable 接口

Implementing compareTo() and Comparable-interface

我正在尝试实施 ComparablecompareTo(),但似乎无法正常工作。我一直在尝试不同的方法,但我真的不明白。我知道我应该实现可比较的接口,并且我需要在使用它之前创建方法 compareTo()(对我来说很奇怪,来自 python 到面向对象编程)。

我想让它比较两个人的年龄,所以我尝试编写如下代码,但似乎无法使用 compareTo()。我收到错误消息:"This method must return an int type",但正如我所见,我只返回 1、-1 和 0,它们 int?

另外,我知道最后打印行是错误的。我怎样才能改变它,例如:"Name1, 25 yrs old, is older than Name2, 21 yrs old"。在 python 中,我可以从列表中提取 2 个特定值并将它们与某些给定方法进行比较;我不确定如何提取 Java.

中的 2 个不同值
import java.util.ArrayList;
import java.util.Random;

class Human implements Comparable<Human>{

    int age;
    String name;

    public Human (int myAge, String myName) {
        name = myName;
        age = myAge;

    }

    public Human() {
        this(randomAge(),randomName());
    }

    public int compareTo(Human o) {
        if (this.age > o.age) {
            return 1;
        }
        if (this.age < o.age) {
            return -1;
        }
        if (this.age == o.age) {
            return 0;
        }
    }

    protected static int randomAge() {
        Random randomGenerator = new Random();      
        return randomGenerator.nextInt(99);
    }

    protected static String randomName() {
        Random randomGenerator = new Random();
        return "Name"+randomGenerator.nextInt(15);
    }

    public int getAge(){
        return age;
    }

    public String getName() {
        return name;
    }

    public String toString() {
        return "\nName: " + name + "\nAge: " + age + " yrs old\n";
    }

    public static void main (String[] args) {

        ArrayList<Human> randomHumans = new ArrayList<Human>();
        for (int j=0;j<2;j++) {
            Human randomPerson = new Human();
            randomHumans.add(randomPerson);
        }
        System.out.println(insert.something.here);
    }

}

所以使用三个 if 语句是行不通的,这就是为什么我可以写一个 if/else if/else 语句,但另一个更简单的解决方案是在 compareTo(Human o)-方法;

return this.age - o.age

然后进行最后的打印;

int b = randomHumans.get(0).compareTo(randomHumans.get(1));

if (b>0) {
    System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is older than "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}
else if (b<0) {
    System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is younger than "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}
else {
    System.out.println(randomHumans.get(0).getName()+", "+randomHumans.get(0).getAge()+" yrs old, is just as old as "+randomHumans.get(1).getName()+", "+randomHumans.get(1).getAge()+" yrs old.");
}