- import java.util.*;
- public class EmployeeSort
- {
- public static void main(String[] args)
- {
- Employee[] staff = new Employee[3];
- staff[0] = new Employee("Guo",1000.0);
- staff[1] = new Employee("Guo",800.0);
- staff[2] = new Employee("Song",1000.0);
- Arrays.sort(staff);
- for(int i=0;i<staff.length;i++)
- {
- Employee e=staff[i];
- System.out.println(e.getName() + " " + e.getSalary());
- }
- }
- }
- class Employee implements Comparable
- {
- public Employee(String name,double salary )
- {
- this.name = name;
- this.salary = salary;
- }
- public String getName()
- {
- return name;
- }
- public double getSalary()
- {
- return salary;
- }
- public void raiseSalary(int byPercent)
- {
- salary = salary * (1 + byPercent / 100.0);
- }
- public int compareTo(Object other)
- //注意返回类型,Java中boolean类型与整型不一样,它只有true和false两种类型,与C++完全不同
- {
- Employee e=(Employee) other;
- if(salary<e.getSalary())
- return -1;
- if(salary>e.getSalary())
- return 1;
- return 0;
- }
- private String name;
- private double salary;
- }
Comparable接口
最新推荐文章于 2024-12-30 09:04:23 发布