Now, what if you have your own custom class like a Dog, Cat, etc instead of a library class like String, Integer, etc?

Here is an example of a JavaTechnology custom object that implements a default sorting logic based on the rank (i.e popularity).

public class JavaTechnology implements Comparable<JavaTechnology>{

 

private String name;

private int rank;   // popularity lower value means more popular

 

public JavaTechnology(String name, int rank){

this.name = name;

this.rank = rank;

}

 

//default implementation by rank alone

@Override

public int compareTo(JavaTechnology technology) {

int rank1 = this.rank;

int rank2 = technology.rank;

if (rank1 > rank2){

return +1;

}else if (rank1 < rank2){

return -1;

}else{

return 0;

}

}

 

//required for printing, displaying, etc.

@Override

public String toString() {

return “(” + name + ” , ” + rank + “)”;

}

}

Now, a simple test class

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

 

public class Sort3Test {

 

public static void main(String[] args) {

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

 

List<javatechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

 

Collections.sort(values); // invokes the compareTo(…) method in JavaTechnology a number of times

 

System.out.println(values);

 

}

 

}

Output:

[(JEE , 1), (Java , 1), (Servlets , 2), (JSP , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]