如何实现Java可比接口?

2022-08-31 09:37:58

我不确定如何在我的抽象类中实现可比较的接口。我有以下示例代码,我用它来尝试解决它:

public class Animal{
    public String name;
    public int yearDiscovered;
    public String population;

    public Animal(String name, int yearDiscovered, String population){
        this.name = name;
        this.yearDiscovered = yearDiscovered;
        this.population = population; }

    public String toString(){
        String s = "Animal name: "+ name+"\nYear Discovered: "+yearDiscovered+"\nPopulation: "+population;
        return s;
    }
}

我有一个测试类,它将创建动物类型的对象,但是我希望在此类中有一个可比较的接口,以便较早的发现排名高于低。我不知道该怎么做。


答案 1

您只需要定义它,即.然后你必须以你喜欢的方式实现方法。Animal implements Comparable<Animal>public class Animal implements Comparable<Animal>compareTo(Animal other)

@Override
public int compareTo(Animal other) {
    return Integer.compare(this.year_discovered, other.year_discovered);
}

使用这个实现,具有更高层次的动物将获得更高的顺序。我希望您能理解这个例子。compareToyear_discoveredComparablecompareTo


答案 2

您需要:

  • 添加到类声明;和implements Comparable<Animal>
  • 实现一个方法来执行比较。int compareTo( Animal a )

喜欢这个:

public class Animal implements Comparable<Animal>{
    public String name;
    public int year_discovered; 
    public String population; 

    public Animal(String name, int year_discovered, String population){
        this.name = name;
        this.year_discovered = year_discovered;
        this.population = population;
    }

    public String toString(){
     String s = "Animal name: "+ name+"\nYear Discovered: "+year_discovered+"\nPopulation: "+population;
     return s;
    }

    @Override
    public int compareTo( final Animal o) {
        return Integer.compare(this.year_discovered, o.year_discovered);
    }
}

推荐