如何实现Java可比较的界面? [英] How to implement the Java comparable interface?
问题描述
我不确定如何在我的抽象类中实现类似的接口。我有以下示例代码,我正在尝试并试图解决它:
I am not sure how to implement a comparable interface into my abstract class. I have the following example code that I am using to try and get my head around it:
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;
}
}
我有一个测试类,可以创建类型的对象然而,我希望在这个类中有一个类似的界面,以便老年的发现排名高于低。我不知道如何解决这个问题。
I have a test class that will create objects of type Animal however I want to have a comparable interface inside this class so that older years of discovery rank higher than low. I have no idea on how to go about this though.
推荐答案
你只需要定义那个动物实现Comparable< Animal>
ie public class Animal实现Comparable< Animal>
。然后你必须以你喜欢的方式实现 compareTo(Animal other)
方法。
You just have to define that Animal implements Comparable<Animal>
i.e. public class Animal implements Comparable<Animal>
. And then you have to implement the compareTo(Animal other)
method that way you like it.
@Override
public int compareTo(Animal other) {
return Integer.compare(this.year_discovered, other.year_discovered);
}
使用 compareTo $ c $的此实现c>,具有较高
year_discovered
的动物将被命令更高。我希望你能用这个例子来理解 Comparable
和 compareTo
。
Using this implementation of compareTo
, animals with a higher year_discovered
will get ordered higher. I hope you get the idea of Comparable
and compareTo
with this example.
这篇关于如何实现Java可比较的界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!