Example for a class implementing comparable interface in Java

When you need some sort of ordering for the classes which you define, you will be going either for a comparable or comparator interface. Consider this example

package test;

import java.util.*;

public class TreeSetTest {

private static Set<Person> s = new TreeSet<Person>();

public static void main(String a[]){
s.add(new Person(20));
s.add(new Person(30));
s.add(new Person(10));
s.add(new Person(50));
System.out.println( s);
}
}

class Person implements Comparable<Person> {
int i;
Person(int i){
this.i = i;
}

public int compareTo(Person o) {
System.out.println(“this.i :: ” + this.i);
int j = o.i;
System.out.println(“j :: ” + j);

if (this.i < j) {
return -1;
} else if (this.i == j) {
return 0;
} else {
return 1;
}
}
public String toString() {
return String.valueOf(“Person ” + i);
}
}

 

Here in this case, the TreeSet API sorts the order of the Objects when you add to it. So, taking this example, if you try to add the Person objects to the TreeSet, it will be comparing the existing object with the object that is inserted and the comparison of objects is done by casting the objects to the Comparable interface and by invoking the compareTo method and the return value of this method determines the position where the object will be placed. When you use a comparable interface, you can sort the Class (in this case, Person) only with the logic you have specified in the compareTo method. But if you want to do different types of sorting of the same instances, then you can use Comparators based on the different instance variables available in the Class which you want to sort. The java.util.Collections class has a overloaded sort method which accepts the comparator to achieve the specific ordering which we would like to have.

The Java Classes which implements the Comparable interfaces are the wrapper classes like Integer, String, Character, Double, Long, Float etc..

To explain about Comparator, consider the following example

package test;

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

 

public class ComparatorExample {

/**
* @param args
*/
public static void main(String[] args) {
List<ComparatorExample.Person> personList = new ArrayList<ComparatorExample.Person>();
ComparatorExample temp = new ComparatorExample();

personList.add(temp.new Person(1, “abc”));
personList.add(temp.new Person(5, “mno”));
personList.add(temp.new Person(3, “xyz”));

System.out.println(“Person List Before sort ::: ” + personList);

IntComparator comparator = new IntComparator();
Collections.sort(personList, comparator);
System.out.println(“Person List after Integer sort ::: ” + personList);

Collections.sort(personList, new StringComparator());
System.out.println(“Pers on List after String sort ::: ” + personList);
}

class Person {
private int index;

private String name;

Person(int index, String name) {
this.index = index;
this.name = name;
}

public String toString() {
return ” Name :: ” + this.name + ” Index :: ” + this.index;
}
}

static class IntComparator implements Comparator<Person> {

public int compare(Person o1, Person o2) {
int i = o1.index;
int j = o2.index;

if (i < j) {
return -1;
} else if (i == j) {
return 0;
} else {
return 1;
}
}

}

static class StringComparator implements Comparator<Person> {

public int compare(Person o1, Person o2) {
String name1 = o1.name;
String name2 = o2.name;

return name1.compareTo(name2);
}
}

}

 

In the above given class, the objects have been sorted both based on the index and the name.

For the other question which you asked,

equals() method is for comparing “equality”. compareTo is for ordering of objects within a collection. Even if compareTo() returns 0, that does not necessarily mean they are “equal”. The concept of “equality” can be applied to all objects (hence it’s defined in the base Object class), but not all objects can have the concept of “ordering” (where one object is “greater than” another).

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Pranay Dhoke says:

    hi …need to learn spring ,,hibernate ,maven ,with JBOSS.
    but sometimes get such error that need someone to guide ..
    can u please guide me ..from where to start ..
    Thanks & Regards

    Pranay!!

Speak Your Mind

*