Java.lang.Comparable is an interface used for sorting
collections. The classes implementing Comparables must implement the
compareTo() method. Here is a simple example of how a comparable can be used.
The example sorts a list of employees on the basis of their age. In this
example we have a simple pojo named Employee.java implementing a
java.lang.Comparable interface by overriding the compareTo method and a main
class to demonstrate the functionality.
Employee.java:
package
com.soft.model;
public
class Employee implements Comparable
private
String name;
private
String department;
private
int age;
public
String getName() {
return name;
}
public
void setName(String name) {
this.name = name;
}
public
String getDepartment() {
return department;
}
public
void setDepartment(String department) {
this.department = department;
}
public
int getAge() {
return age;
}
public
void setAge(int age) {
this.age = age;
}
@Override
public
int compareTo(Object o) {
if(this.age>((Employee)o).getAge()){
return 1;
} else if(this.age<((Employee)o).getAge()){
return -1;
} else{
return 0;
}
}
}
ComparableExample:
package
com.soft.examples;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
import
com.soft.model.Employee;
public
class ComparableExample {
public static void main(String[]
args) {
List<Employee>
list= new ArrayList<Employee>();
Employee e=new
Employee();
e.setName("Danial
Fritz");
e.setDepartment("Field
Based Development");
e.setAge(36);
list.add(e);
e=new
Employee();
e.setName("Denis
Khoo");
e.setDepartment("Project
Management");
e.setAge(30);
list.add(e);
e=new Employee();
e.setName("Joe
Kum");
e.setDepartment("Adminstration");
e.setAge(40);
list.add(e);
e=new
Employee();
e.setName("Anil
Kumar");
e.setDepartment("Information
Technology");
e.setAge(26);
list.add(e);
System.out.println("************
Before Sorting ***********");
for (int i=0;i<
list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
System.out.println("************
Age Sorting through Comparable ***********");
Collections.sort(list);
for (int i=0;i<
list.size();i++){
System.out.println(list.get(i).getName()+"-----"+list.get(i).getDepartment()+"-----"+list.get(i).getAge());
}
}
}
This
functionality can also be achieved with a java.util.Comparator, the implementation
of which is given at
The
differences between java.util.Comparator and java.lang.Comparable interfaces
are given at
No comments:
Post a Comment