I was trying to develop an application in which the arraylist will be sorted by first name and if the name of two persons are same then the further comparison will be done on the basis of their salary, for this an comparator has to be made please advise how to make that custom comparator..below is my program rite now which is only doing comparison the basis of salary rite now..!
package saxbean;
class Emp //implements Comparable
{
String name,job;
int salary;
public Emp(String n,String j,int sal)
{
name=n;
job=j;
salary=sal;
}
public void display()
{
System.out.println(name+"\t"+job+"\t"+salary);
}
public boolean equals(Object o)
{
Emp p=(Emp)o;
return this.name.equals(p.name)&&this.job.equals(p.job) &&this.salary==p.salary;
}
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
/* public int compareTo(Object o)
{
Emp e=(Emp)o;
return this.name.compareTo(e.name);
//return this.job.compareTo(e.job);
// return this.salary-e.salary;
}*/
}
MY Comprator is …
import java.util.Comparator;
class SalaryComparator implements Comparator {
public int compare(Object paramObject1, Object paramObject2) {
Emp localEmp1 = (Emp) paramObject1;
Emp localEmp2 = (Emp) paramObject2;
return localEmp1.salary - localEmp2.salary;
}
}
My main class is…
class EmpListDemo
{
public static void main(String arg[])
{
List list=new ArrayList ();
list.add(new Emp("Ram","Trainer",34000));
list.add(new Emp("Sachin","Programmer",24000));
list.add(new Emp("Ram","Trainer",34000));
list.add(new Emp("Priyanka","Manager",54000));
list.add(1,new Emp("Ravi","Administrator",44000));
list.add(new Emp("Anupam","Programmer",34000));
list.add(new Emp("Priyanka","Manager",54000));
list.add(new Emp("Sachin","Team Leader",54000));
System.out.println("There are "+list.size()+" elements in the list.");
//original list
System.out.println("Content of list are : ");
ListIterator itr1=list.listIterator();
while(itr1.hasNext())
{
Emp e=(Emp)itr1.next();
e.display();
}
System.out.println("*****************");
System.out.println("Sort Object according to Salary");
Collections.sort(list,new SalaryComparator());
System.out.println("Content of list are : ");
itr1=list.listIterator();
while(itr1.hasNext())
{
Emp e=(Emp)itr1.next();
e.display();
}
}
}
but please advise how to develop an application in which the arraylist will be sorted by first name and if the name of two persons are same then the further comparison will be done on the basis of their salary..!!
1 Answer