Comparator接口,类数组排序

时间:2023-02-08 02:52:30
package zzy;
import static java.lang.System.*;
import java.util.*;
/**
 *
 * @author Zhu Zhengyan
 */
public class zzy8 {
    public static void main(String[] args)
    {
        Emp[] staff = new Emp[3];
        staff[0] = new Emp("zzy",35000);
        staff[1] = new Emp("zkb",75000);
        staff[2] = new Emp("lt",48000);
        Arrays.sort(staff);
        for(Emp e:staff)
            out.println("name = "+e.getName()+",salary = "+e.getSalary());
    }
}


class Emp implements Comparable<Emp>
{
    private String name;
    private double salary;
    public Emp(String name,double salary)
    {
        this.name = name;
        this.salary = salary;
    }
    public String getName()
    {
        return name;
    }
    public double getSalary()
    {
        return salary;
    }
    public void raiseSalary(double byPercent)
    {
        double raise = salary * byPercent / 100;
        salary += raise;
    }
    public int compareTo(Emp a)
    {
        return Double.compare(salary, a.salary);   //Double.compare方法,如果第一个参数小于第二个参数,返回一个负值,相等返回0,否则返回正值
    }                                             
}