簡體   English   中英

實現compareTo()和Comparable-interface

[英]Implementing compareTo() and Comparable-interface

我正在嘗試實現ComparablecompareTo() ,但似乎無法使其正常工作。 我一直在嘗試不同的方法,但我真的不明白。 我知道我應該實現可比的接口,並且在使用它之前需要創建方法compareTo() (對我來說很奇怪,從python到面向對象的編程)。

我想比較兩個人的年齡,因此我嘗試編寫如下所示的代碼,但似乎無法使用compareTo()。 我收到錯誤消息:“此方法必須返回int類型”,但是正如我所看到的,我只返回1,-1和0,它們 int嗎?

另外,我知道最后的打印行是錯誤的。 我該如何更改它,例如說:“ Name1,年齡25歲,比Name2,年齡21歲”。 在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) -method;方法中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM