• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Comparable Interface

November 14, 2011 By j2eereference

Let’s understand the use of comparable interface in java with an example:  We have an Employee class which has two attributes firstName and age.  Now let’s look at how can we sort these Employee instances by salary? We can, of course, write our own code to sort them using any sorting algorithm, but the easy solution is to implement the java.lang.Comparable interface.

Here the Employee class implements the “java.lang.Comparable” interface and in turn implement the compareTo() method which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. This method will throw classCastException if the two objects are not instances of the Employee class.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Employee implements Comparable {
 
private int sal;
private String fistName;
 
public int getSal() {
return sal;
}
public void setSal(int sal) {
this.sal = sal;
}
public String getFistName() {
return fistName;
}
public void setFistName(String fistName) {
this.fistName = fistName;
}
@Override
public int compareTo(Object nextEmployee) {
if(!(nextEmployee instanceof Employee)){
throw new ClassCastException("Invalid object");
}
 
int sal = ((Employee) nextEmployee).getSal();
if(this.getSal() > sal)
return 1;
else if ( this.getSal() < sal )
return -1;
else
return 0;
}
@Override
public String toString() {
return this.sal+"";
}
}

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TestComparable
{
 
public static void main(String[] args) {
Employee emp1 = new Employee();
emp1.setSal(10000);
Employee emp2 = new Employee();
emp2.setSal(30000);
if(emp1.compareTo(emp2) > 0)
{
   System.out.println("emp1 is getting more salary");
  }
else if(emp1.compareTo(emp2)< 0) {
   System.out.println("emp2 is getting more salary");
  }
  else if(emp1.compareTo(emp2)== 0) {
    System.out.println("same salary");
  }
}
}

Output :

emp2 is getting more salary

Comparable interface to sort the Objects

We can sort the objects by using the comparable interface as below.

 

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
 
public class ComparableDemo {
public static void main(String[] args) {
List empList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setSal(10000);
empList.add(emp1);
Employee emp2 = new Employee();
emp2.setSal(45325);
empList.add(emp2);
Employee emp3 = new Employee();
emp3.setSal(7823);
empList.add(emp3);
Employee emp4 = new Employee();
emp4.setSal(45);
empList.add(emp4);
Employee emp5 = new Employee();
emp5.setSal(30000);
empList.add(emp5);
Collections.sort(empList);
System.out.println(empList);
}
}

Output

[45, 7823, 10000, 30000, 45325]

 

Related Posts

  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?
  • How to avoid deadlock in java ?

Filed Under: Core Java

Reader Interactions

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.