[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.

This question is related to java comparable

The answer is


Use a Comparator...

    public class AnimalAgeComparator implements Comparator<Animal> {

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

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


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

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

}

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.

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.


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


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

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.


Here's the code to implement java comparable interface,

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

You need to:

  • Add implements Comparable<Animal> to the class declaration; and
  • Implement a int compareTo( Animal a ) method to perform the comparisons.

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

  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.

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