如何实现Java中的可比较接口?

114

我不确定如何将Comparable接口实现到我的抽象类中。以下是我正在使用的示例代码,以尝试理解它:

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

我有一个测试类,将创建类型为Animal的对象,但是我想在这个类内部拥有可比较的接口,以便更高年份的发现排名比低年份的高。但是我不知道如何去做。


4
查看Comparable的文档。按照文档指示的方式实现它告诉你的方法。 - Cairnarvon
3
我查看了关于Java的文档和其他来源,试图弄清楚它,但出于某种原因我还是不理解。我知道这是件简单的事情,但有时候就是会遇到这种情况。 - Softey
很多例子也会在类外进行比较,但我想在类内进行比较。 - Softey
3
请考虑将变量名称 "year_discovered" 更改为 Java 命名规范的 "yearDiscovered"。 - tstorms
我已将year_discovered更改为yearDiscovered。这是自学Python时养成的可怕习惯。谢谢。 - Softey
9个回答

168

你只需要定义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);
}

利用这个 compareTo 的实现方式,年代更晚的动物将会排在更高的位置。通过这个例子,我希望你能够理解 ComparablecompareTo 的作用。


2
在Android中,需要API 19。 - Hamzeh Soboh
替代方案为:return ((Integer)this.level).compareTo(other.level); - Hamzeh Soboh

37

您需要:

  • 在类声明中添加 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);
    }
}

7
当你在使用compareTo()方法时,我建议你记住一些关键事实:
  1. CompareTo方法必须与equals方法保持一致。例如,如果两个对象通过equals()相等,则compareTo()必须返回零,否则如果这些对象存储在SortedSet或SortedMap中,则它们将无法正常工作。
  2. 与equals()返回false的情况不同,如果当前对象与null对象进行比较,则CompareTo()必须抛出NullPointerException异常。
阅读更多:http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3

1

Emp类需要实现Comparable接口,因此我们需要覆盖其compareTo方法。

import java.util.ArrayList;
import java.util.Collections;


class Emp implements Comparable< Emp >{

    int empid;
    String name;

    Emp(int empid,String name){
         this.empid = empid;  
         this.name = name;

    }


    @Override
    public String toString(){
        return empid+" "+name;
    }

    @Override
    public int compareTo(Emp o) {

     if(this.empid==o.empid){
       return 0; 
     } 
     else if(this.empid < o.empid){
     return 1;
     }
     else{
       return -1;
     }
    }
}

public class JavaApplication1 {


    public static void main(String[] args) {

    ArrayList<Emp> a= new ArrayList<Emp>();

    a.add(new Emp(10,"Mahadev"));
      a.add(new Emp(50,"Ashish"));
      a.add(new Emp(40,"Amit"));
      Collections.sort(a);
      for(Emp id:a){
      System.out.println(id);
      }
    }

}

我正在将其与员工ID进行比较。 - Mahadev Mane

1
在您的类中实现Comparable<Animal>接口,并提供int compareTo(Animal other)方法的实现。查看此帖子

1

0

从源代码中可能的替代方法Integer.compare,需要API版本19

public int compareTo(Animal other) { return Integer.valueOf(this.year_discovered).compareTo(other.year_discovered); }

这个替代方法不需要使用API版本19


-1

使用比较器...

    public class AnimalAgeComparator implements Comparator<Animal> {

@Override
public int compare(Animal a1, Animal a2) {
  ...
}
}

1
OP要求使用Comparable而不是Comparator。 - Abimaran Kugathasan
但我认为在这种情况下,比较器是更好的解决方案。您可以给它一个名称,让比较器进行比较。 - pL4Gu33
1
拥有比较器的唯一原因是具有不同的排序类型。否则,使类可比较是更好的解决方案,因为对象是可比较的,可以直接在 TreeMap 或任何其他集合中使用。 - Vargan

-5

通过实现一个公共类来实现 Comparable,可以轻松地完成这件事。这将允许您使用 compareTo 方法,该方法可用于任何其他您希望进行比较的对象。

例如,您可以按照以下方式实现它:

public String compareTo(Animal oth) 
{
    return String.compare(this.population, oth.population);
}

我认为这可能解决你的目的。


3
"String does not have compare"的意思是“字符串没有比较函数”。 - Kennedy Nyaga
在你把代码粘贴到这里之前,你应该先测试它。 - user8389458

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接