Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Comparable Example

  1. /*
  2. Java Comparable example.
  3. This Java Comparable example describes how java.util.Comparable
  4. interface is implemented to compare user defined classe's objects.
  5. */
  6.  
  7. import java.util.*;
  8.  
  9. /*
  10. Comparable interface is used to make user defined class's objects comparable.
  11. This interface declares one method compareTo(Object object)
  12. and determines how objects can be compared to with each other.
  13. */
  14.  
  15. /*
  16. Implement java.util.Comparable interface to make class objects comparable.
  17. */
  18.  
  19. class Employee implements Comparable{
  20.    
  21.     private int age;
  22.    
  23.     public void setAge(int age){    
  24.         this.age=age;
  25.     }
  26.    
  27.     public int getAge(){    
  28.         return this.age;    
  29.     }
  30.    
  31.     /*
  32.    
  33.     Signature of compareTo method is,    
  34.     public int compareTo(Object object).
  35.    
  36.     compareTo method should return 0 if both objects are equal,
  37.     1 if first grater than other and -1 if first less than the
  38.     other object of the same class.
  39.    
  40.     */
  41.    
  42.     public int compareTo(Object otherEmployee){
  43.    
  44.         /*
  45.         If passed object is of type other than Employee, throw ClassCastException.
  46.         */
  47.        
  48.         if(!(otherEmployee instanceof Employee)){
  49.             throw new ClassCastException("Invalid object");
  50.         }
  51.        
  52.         int age = ((Employee) otherEmployee).getAge();
  53.        
  54.         if(this.getAge() > age)    
  55.             return 1;
  56.         else if ( this.getAge() < age )
  57.             return -1;
  58.         else
  59.             return 0;
  60.    
  61.     }
  62.  
  63. }
  64.  
  65. public class JavaComparableExample{
  66.    
  67.     public static void main(String args[]){
  68.        
  69.         /*
  70.         Create two different Employee objects, so that we can compare them.
  71.         */
  72.        
  73.         Employee one = new Employee();        
  74.         one.setAge(40);
  75.        
  76.         Employee two = new Employee();        
  77.         one.setAge(30);
  78.        
  79.         /*
  80.         Use compareTo method to determine which employee is younger
  81.         */
  82.        
  83.         if(one.compareTo(two) > 0) {        
  84.             System.out.println("Employee one is elder than employee two!");
  85.        
  86.         } else if(one.compareTo(two) < 0) {        
  87.             System.out.println("Employee one is younger than employee two!");        
  88.        
  89.         } else if(one.compareTo(two) == 0) {        
  90.             System.out.println("Both employees are same!");        
  91.         }
  92.    
  93.     }
  94.  
  95. }
  96.  
  97. /*
  98. OUTPUT of the above given Java Comparable Example would be:
  99. Employee one is elder than employee two!
  100. */
Your rating: None Average: 4.4 (14 votes)
Share this
Anonymous's picture

Simple and good explaination.

Simple and good explaination.
Anonymous's picture

can anyone xplian me servlet

can anyone xplian me servlet
Anonymous's picture

Servlets are the

Servlets are the webcomponents which respond to the client request dynamically from the webservers or application servers. They are the good combination of the Business Logic and the Presentation layer , as it combines both in itself. We can develop an online application with the help of servlet in combination with other files like web.xml (for deployement description ) and html files (for views). so we need to write our java class file by implementing or extending some of the servlet-api's interfaces or classes ,
Anonymous's picture

Servlet is a middleware

Servlet is a middleware which is capable of taking a HttpRequest for a java application, it is simply used to achieve interoperability between java and other hetrogenous system. the definition given before is absolutely wrong and insensitive ignore that definition and follow my definition
Anonymous's picture

Hi, good work. But if i have

Hi, good work. But if i have hundred employees then do i need to write if else conditions for all of those. I don't think that is the case. And i need a small program using Comparable interface. For example i have an Array list with 5 elements, i just want to override the comparTo() method. Please do me this favor. Thanks in advance.
Anonymous's picture

Employee emps[] = {new

Employee emps[] = {new Employee(78), new Employee(45), new Employee(64), new Employee(33), new Employee(22)};
Arrays.sort(emps);
System.out.print(((Employee)emps[0]).getAge());
The output is 22.
Anonymous's picture

Have a arraylist for those

Have a arraylist for those 100 employees and store their age in the arraylist
Anonymous's picture

No , you don't need to write

No , you don't need to write at a time only two objects get compared using Comparable or Comparator interface in Java . all magic is done by Collections.sort() method which is used to sort the item inside collection, just store your element in Java arraylist and use Collections.sort() for sorting them
Anonymous's picture

The ultimate beauty lies in

The ultimate beauty lies in simplicity :-) Simple and superb example :-) Thanks
Anonymous's picture

For who have hundred

For who have hundred employees. Employee emps[] = {new Employee(78), new Employee(45), new Employee(64), new Employee(33), new Employee(22)}; Arrays.sort(emps); System.out.print(((Employee)emps[0]).getAge()); output is 22.
Anonymous's picture

There is no point in if you

There is no point in if you are directly calling compareTo() method.. It could have been any other custom method by developer why going for comparable interface???? If any of the bean(in your case Employee), since is implementing the Comparable interface, when explicit call like Arrays.sort(bean) is called - will use compareTo() internally to determine the order in which the bean array should be sorted and this is how Developers burden can be reduced. Not as you have explicitly called compareTo() in your JavaComparableExample class. Once Arrays.sort() is called, your array should be in the order as determined by the overriden behaviour of the compareTo()..
Anonymous's picture

are you saying that this guy

are you saying that this guy incurred in dupliciousness by having both, the compare and the sort array methods do the same thing within the same main().
vj_agl's picture

Simple n Gud 1 I had

Simple n Gud 1

I had followoing question in my mind  ----------------------- For 100 emp how do we perform search opeartion usinf compareTo


But lator came to know

Arrays.sort() will make use of compareTo to sort emp age !!! thats gud too
Anonymous's picture

nice articles

nice articles
Anonymous's picture

Please check the

Please check the ComparableExample . Comparable Interface is not present in java.util package. It is present in java.lang package......
Anonymous's picture

STRONGLY AGREE

STRONGLY AGREE

Post new comment