-> Comparable is an interface of comparing the objects with other objects os the same type. This is also called "natural ordering"
-> by using compare interface, we can sort the elements based on single data member only.
-> It provides single method name as compareTo(object) and provides single sorting sequence only.
-> The interface found in java.lang.package
compareTo(Object obj) method
The method used to compare the current object with specified object. Please find the below return values
positive integer = if the current object is greater than the specified object.
negative integer = if the current object is less than the specified object.
zero = if the current object is equal to the specified object.
Example 1: Sort by Integer Value (Ascending Order) by using Comparable
import java.util.*;
// User - Defined Class
class Employee implements Comparable<Employee>{
int empid;
String empname;
int empage;
Employee(int empid,String empname,int empage){
this.empid=empid;
this.empname=empname;
this.empage=empage;
}
public int compareTo(Employee st){
if(empage==st.empage)
return 0;
else if(empage>st.empage)
return 1;
else
return -1;
}
}
// Main Class
public class TestSort1{
public static void main(String args[]){
ArrayList<Employee> al=new ArrayList<Employee>();
al.add(new Employee(1,"Ajith",23));
al.add(new Employee(6,"Vijay",27));
al.add(new Employee(4,"Surya",21));
Collections.sort(al);
for(Employee st:al){
System.out.println(st.empid+" "+st.empname+" "+st.empage);
}
}
}
Output
4 Surya 21
1 Ajith 23
6 Vijay 27
********************************************************
Example 2: Sort by Integer Value (Decending Order) by using Comparable
import java.util.*;
// User - Defined Class
class Employee implements Comparable<Employee>{
int empid;
String empname;
int empage;
Employee(int empid,String empname,int empage){
this.empid=empid;
this.empname=empname;
this.empage=empage;
}
public int compareTo(Employee st){
if(empage==st.empage)
return 0;
else if(empage<st.empage)
return 1;
else
return -1;
}
}
// Main Class
public class TestSort1{
public static void main(String args[]){
ArrayList<Employee> al=new ArrayList<Employee>();
al.add(new Employee(1,"Ajith",23));
al.add(new Employee(6,"Vijay",27));
al.add(new Employee(4,"Surya",21));
Collections.sort(al);
for(Employee st:al){
System.out.println(st.empid+" "+st.empname+" "+st.empage);
}
}
}
Output
6 Vijay 27
1 Ajith 23
4 Surya 21
No comments:
Post a Comment