我正在尝试开发一个应用程序,其中 arraylist 将按名字排序,如果两个人的名字相同,那么将根据他们的薪水进行进一步比较,为此必须进行比较,请告知如何制作那个自定义比较器..下面是我现在的程序仪式,它现在只是比较薪水仪式的基础......!
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;
}*/
}
我的比较器是...
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;
}
}
我的主要课程是...
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();
}
}
}
但是请告知如何开发一个应用程序,其中arraylist 将按名字排序,如果两个人的名字相同,那么将根据他们的薪水进行进一步的比较..!!