Softey Softey - 7 months ago 39
Java Question

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 year_discovered;
public String population;

public Animal(String name, int year_discovered, String population){ = 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;

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> i.e. public class Animal implements Comparable<Animal>. And then you have to implement the compareTo(Animal other) method that way you like it.

public int compareTo(Animal other) {
    return, 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.