iwebie
HOME MOVIES TV SHOWS SPORTS GENERAL
 RSSPRIVACY
 

Java Comparable Interface
Posted by admin on June 10th, 2008

Watch over 100,000 movies and TV shows on your PC

Java Comparable compareTo Method Usage

We need to implement the Comparable Interface, if we have to sort user defined objects in Java. The compatable interface has a compareTo() method that is used by the sort() method of the Array’s Class.

In this code Employee class is implementing Comparable interface and overridden the compareTO() method. The ComparableDemo.java class uses the Arrays.sort(any comparableObject) which internally uses the compareTo() method of Employee class and sorts the Employees.

[sourcecode language='java']
import java.util.Arrays;

class Employee implements Comparable {

private int empId;
private String name;

public Employee(int id, String name) {
this.empId = id;
this.name = name;
}

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int compareTo(Object o) {
Employee obj = (Employee) o;

if (this.getEmpId() < obj.getEmpId()) {
return -1;
} else if (this.getEmpId() > obj.getEmpId()) {
return 1;
}
return 0;
}

public String toString() {
return name;
}
}

public class ComparableDemo {

public static void main(String[] args) {
// Sorting the Employees based on Emplyee ID

Employee[] emps = new Employee[3];
emps[0] = new Employee(10, “Bob”);
emps[1] = new Employee(30, “Sob”);
emps[2] = new Employee(20, “Rob”);
System.out.println(”Employees are : ” + emps[0] + “\t” + emps[1] + “\t”
+ emps[2]);
Arrays.sort(emps);
System.out.println(”Employees are : ” + emps[0] + “\t” + emps[1] + “\t”
+ emps[2]);
}
}
[/sourcecode]

Bookmark Article
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Propeller

Leave a Reply

Most Popular

Watch over 100,000 movies and TV shows on your PC
Recent Posts

  • Watch Crazy on the Outside Online Free
  • Watch It’s Complicated Full Video Online
  • Watch Leap Year Free Stream Online
  • Watch Manchester United vs Birmingham Live Stream
  • Watch Avatar Online Stream
  • Watch Nine Online Video
  • Watch Crazy Heart Full Stream
  • Modern Family Season 1 Episode 11 | Watch Modern Family s01e11 Up All Night Full Episode
  • Burnley vs Arsenal EPL | Watch Burnley vs Arsenal Live Stream
  • Watch The Princess and the Frog Online Free
Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
Powered by WordPress