
I want to know the use of Comparable Interface. Please provide me one example

Comparable interface is used to define the natural sort order of a class.List of objects that implement this interface can be sorted automatically by sort method of the list interface. This interface has compareTo() method that is used by the sort() method of the list.
Here is an example that compares two ages using Comparable Interface.
import java.util.*;
class Person implements Comparable{
int age;
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
public int compareTo(Object ob){
if(!(ob instanceof Person)){
throw new ClassCastException("Invalid object");
}
int age = ((Person) ob).getAge();
if(this.getAge() > age)
return 1;
else if ( this.getAge() < age )
return -1;
else
return 0;
}
}
public class ComparableExample{
public static void main(String args[]){
Person one = new Person();
one.setAge(35);
Person two = new Person();
one.setAge(30);
if(one.compareTo(two) > 0) {
System.out.println("Person one is elder than Person two!");
} else if(one.compareTo(two) < 0) {
System.out.println("Person one is younger than Person two!");
} else if(one.compareTo(two) == 0) {
System.out.println("Both Persons are same!");
}
}
}

public class Employee implements Comparable<Employee> {
int empId;
String eName;
public Employee(int empId, String eName) {
super();
this.empId = empId;
this.eName = eName;
}
@Override
public String toString() {
return "ID:"+empId+"NAME:"+eName;
}
@Override
public int compareTo(Employee e) {
return eName.compareTo(e.eName);
}
}
import java.util.Iterator;
import java.util.TreeSet;
public class EmpMain {
/**
* @param args
*/
public static void main(String[] args) {
TreeSet<Employee> ts =new TreeSet<Employee>();
ts.add(new Employee(123,"vijay"));
ts.add(new Employee(98,"kumar"));
ts.add(new Employee(100,"abhi"));
ts.add(new Employee(50,"dhruv"));
ts.add(new Employee(150,"sasi"));
for (Iterator iterator = ts.iterator(); iterator.hasNext();) {
Employee employee = (Employee) iterator.next();
System.out.println(employee);
}
}
}

output:
ID:100NAME:abhi ID:50NAME:dhruv ID:98NAME:kumar ID:150NAME:sasi ID:123NAME:vijay
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.