package Coparable_Std;
//Sort Employee OBJECT according to Names.......
public class Employee implements Comparable<Employee>
{
int e_id;
int dept_id;
String name;
Employee(int eid,int dept,String name)
{
this.e_id = eid;
this.dept_id = dept;
this.name = name;
}
@Override
public int compareTo(Employee emp)
{
return this.name.compareTo(emp.name); //** For Strings we don't need to do anything
} //coz String has it own implemented compareTo() for sorting
}
//Sort Employee OBJECT according to Names.......
public class Employee implements Comparable<Employee>
{
int e_id;
int dept_id;
String name;
Employee(int eid,int dept,String name)
{
this.e_id = eid;
this.dept_id = dept;
this.name = name;
}
@Override
public int compareTo(Employee emp)
{
return this.name.compareTo(emp.name); //** For Strings we don't need to do anything
} //coz String has it own implemented compareTo() for sorting
}
--------
--------
package Coparable_Std;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Employee_Runner {
public static void main(String[] args)
{
Employee e1 = new Employee(104,072,"Giridhar");
Employee e2 = new Employee(145,911,"Amit");
Employee e3 = new Employee(167,053,"Mallik");
Employee e4 = new Employee(134,884,"Pranav");
Employee e5 = new Employee(101,445,"Ginny");
ArrayList list = new ArrayList();
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
list.add(e5);
Collections.sort(list);
Iterator itr = list.iterator();
while(itr.hasNext())
{
Employee emp = (Employee)itr.next();
System.out.println(emp.e_id+" "+emp.dept_id+" "+emp.name);
}
}
}
No comments:
Post a Comment