简体   繁体   English

如何实现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.我不知道该怎么做。

You just have to define that Animal implements Comparable<Animal> ie public class Animal implements Comparable<Animal> .您只需定义Animal implements Comparable<Animal>public class Animal implements Comparable<Animal> And then you have to implement the compareTo(Animal other) method that way you like it.然后你必须以你喜欢的方式实现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_discovered will get ordered higher.使用compareTo的这种实现,具有更高year_discovered的动物将获得更高的排序。 I hope you get the idea of Comparable and compareTo with this example.我希望您通过这个示例了解ComparablecompareTo的概念。

You need to:你需要:

  • Add implements Comparable<Animal> to the class declaration;在类声明中添加implements Comparable<Animal> and
  • Implement a int compareTo( Animal a ) method to perform the comparisons.实现一个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);
    }
}

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

  2. CompareTo() must throw NullPointerException if current object get compared to null object as opposed to equals() which return false on such scenario.如果当前对象与 null 对象进行比较,CompareTo() 必须抛出 NullPointerException,而不是在这种情况下返回 false 的 equals()。

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

Implement Comparable<Animal> interface in your class and provide implementation of int compareTo(Animal other) method in your class.在您的类中实现Comparable<Animal>接口并在您的类中提供int compareTo(Animal other)方法的实现。 See This Post 看到这篇文章

You would need to implement the interface and define the compareTo() method.您需要实现接口并定义 compareTo() 方法。 For a good tutorial go to - Tutorials point link or MyKongLink要获得好的教程,请访问 -教程点链接MyKongLink

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

}

Possible alternative from the source code of Integer.compare method which requires API Version 19 is :需要API Version 19Integer.compare方法的源代码的可能替代方法是:

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

This alternative does not require you to use API version 19 .此替代方法不需要您使用API version 19

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

Use a Comparator...使用比较器...

    public class AnimalAgeComparator implements Comparator<Animal> {

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

Here is another example这是另一个例子

public class Book implements Comparable<Book>{
    int id;
    String name="";
    double price;
    
    public Book(int id, String name, double price) {
        this.id = id;
        setName(name);
        setPrice(price);
    }

    public void setName(String name) {
        this.name = "";
        this.name += name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    /**
     * return this as a String in the required format
     */
    @Override
    public String toString() {
        String result = String.format("%5d %-45s %10.2f", this.id, this.name, this.price);
        return result;
    }
    @Override
    public int compareTo(Book compareBook) {
        Double comparePrice = ((Book)compareBook).price;
        
        return (int)(comparePrice-this.price);
    }
}

This thing can easily be done by implementing a public class that implements Comparable.这件事可以通过实现一个实现 Comparable 的公共类来轻松完成。 This will allow you to use compareTo method which can be used with any other object to which you wish to compare.这将允许您使用 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.我认为这可能会解决您的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM