114

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.

Softey
  • 1,451
  • 3
  • 21
  • 42
  • 4
    Look at the documentation for `Comparable`. Implement the method it tells you to in the way it tells you to. – Cairnarvon Feb 07 '14 at 11:24
  • 3
    I have had a look at the Java documentation for it and other sources to try and get my head around it but for some reason I don't understand it. I know it's something simple but it's just one of those things. – Softey Feb 07 '14 at 11:25
  • A lot of examples also do the comparison outside of the class but I want to do it inside. – Softey Feb 07 '14 at 11:27
  • 3
    Also consider changing variable name "year_discovered" to the java convention "yearDiscovered". – tstorms Feb 07 '14 at 11:29
  • I have changed the year_discovered to yearDiscovered. Terrible habits from doing self taught python. Thank you – Softey Feb 07 '14 at 11:31

9 Answers9

168

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

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.

phoenix
  • 7,988
  • 6
  • 39
  • 45
user1983983
  • 4,793
  • 2
  • 15
  • 24
37

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);
    }
}
MT0
  • 143,790
  • 11
  • 59
  • 117
7

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

guest
  • 91
  • 1
  • 1
1

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

Community
  • 1
  • 1
Sanjeev
  • 9,876
  • 2
  • 22
  • 33
1

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

Gyan
  • 1,176
  • 1
  • 12
  • 26
1

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

}
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
Mahadev Mane
  • 810
  • 8
  • 11
0

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.

recepinanc
  • 176
  • 1
  • 13
-1

Use a Comparator...

    public class AnimalAgeComparator implements Comparator<Animal> {

@Override
public int compare(Animal a1, Animal a2) {
  ...
}
}
pL4Gu33
  • 2,045
  • 16
  • 38
  • 1
    OP asking Comparable, not Comparator – Abimaran Kugathasan Feb 07 '14 at 11:26
  • But i think in this case a comparator is the better solution. You can give it a name what the comparator compares. – pL4Gu33 Feb 07 '14 at 11:33
  • 1
    The only reason to have comparator is to have different sorting types. Otherwise, making the class comparable is a better solution because the object is comparable, and can be used in a treemap or any other collection directly – Vargan Sep 24 '15 at 13:18
-5

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.

D3X
  • 547
  • 3
  • 20