如何实现Java可比较接口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21626439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:44:07  来源:igfitidea点击:

How to implement the Java comparable interface?

javacomparable

提问by Softey

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.

我有一个测试类,它将创建 Animal 类型的对象,但是我希望在这个类中有一个可比较的接口,以便较旧的发现排名高于低。我不知道如何解决这个问题。

采纳答案by user1983983

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.

你只需要定义Animal implements Comparable<Animal>ie public class Animal implements Comparable<Animal>。然后你必须compareTo(Animal other)按照你喜欢的方式实现方法。

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

Using this implementation of compareTo, animals with a higher year_discoveredwill get ordered higher. I hope you get the idea of Comparableand compareTowith this example.

使用 的这种实现compareTo,具有更高的动物year_discovered将获得更高的排序。我希望你的想法ComparablecompareTo这个例子。

回答by Sanjeev

Implement Comparable<Animal>interface in your class and provide implementation of int compareTo(Animal other)method in your class.See This Post

Comparable<Animal>在类中实现接口并在类中提供int compareTo(Animal other)方法的实现。看到这篇文章

回答by Gyan

You would need to implement the interface and define the compareTo() method. For a good tutorial go to - Tutorials point linkor MyKongLink

您需要实现该接口并定义 compareTo() 方法。对于一个好的教程去 -教程点链接MyKongLink

回答by pL4Gu33

Use a Comparator...

使用比较器...

    public class AnimalAgeComparator implements Comparator<Animal> {

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

回答by MT0

You need to:

你需要:

  • Add implements Comparable<Animal>to the class declaration; and
  • Implement a int compareTo( Animal a )method to perform the comparisons.
  • 添加implements Comparable<Animal>到类声明;和
  • 实现一个int compareTo( Animal a )方法来执行比较。

Like this:

像这样:

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

回答by D3X

This thing can easily be done by implementing a public class that implements Comparable. This will allow you to use compareTo method which can be used with any other object to which you wish to compare.

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

for example you can implement it in this way:

例如,您可以通过以下方式实现它:

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

I think this might solve your purpose.

我认为这可能会解决您的目的。

回答by guest

While you are in it, I suggest to remember some key facts about compareTo() methods

当你在里面时,我建议记住一些关于 compareTo() 方法的关键事实

  1. CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.

  2. CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.

  1. CompareTo 必须与 equals 方法一致,例如,如果两个对象通过 equals() 相等,则 compareTo() 必须返回零,否则如果这些对象存储在 SortedSet 或 SortedMap 中,它们将无法正常运行。

  2. 如果当前对象与 null 对象进行比较,CompareTo() 必须抛出 NullPointerException,而不是 equals() 在这种情况下返回 false。

Read more: http://javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3

阅读更多:http: //javarevisited.blogspot.com/2011/11/how-to-override-compareto-method-in.html#ixzz4B4EMGha3

回答by recepinanc

Possible alternative from the source code of Integer.comparemethod which requires API Version 19is :

Integer.compare需要的方法源代码的可能替代方法API Version 19是:

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

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

This alternative does notrequire you to use API version 19.

这种替代并不要求您使用API version 19

回答by Mahadev Mane

Emp class needs to implement Comaparable interface so we need to Override its compateTo method.

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

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

}

回答by Shiva

Here's the code to implement java comparable interface,

这是实现java可比接口的代码,

// adding implements comparable to class declaration
public class Animal implements Comparable<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;
    }

    @Override
    public int compareTo(Animal other)  // compareTo method performs the comparisons 
    {
        return Integer.compare(this.year_discovered, other.year_discovered);
    }
}