日期:2014-05-20 浏览次数:20746 次
package list;
import java.util.*;
public class EmployeeSortTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tom", 3500);
staff[1] = new Employee("Jack", 2500);
staff[2] = new Employee("Rose", 5600);
Arrays.sort(staff);
for (Employee e:staff) {
System.out.println("Name = " + e.getName() + " Salary = " + e.getSalary());
}
Manager[] managers = new Manager[4];
managers[0] = new Manager("Lucy", 3500, 1000);
managers[1] = new Manager("Keith", 4000, 2000);
managers[2] = new Manager("Jennifer", 5600, 500);
managers[3] = new Manager("Tony", 5000, 1500);
// 这里想实现按照bonus排序
Arrays.sort(managers);
for (Manager m:managers) {
System.out.println("Name = " + m.getName() + " Salary = " + m.getSalary() + " Bonus = " + m.getBonus());
}
}
}
class Manager extends Employee {
private double bonus;
public Manager(String n, double s, double b) {
super(n, s);
bonus = b;
}
public double getBonus() {
return bonus;
}
// 直接在这里写,不起作用,知道是错的,不知道该咋写
public int compareTo(Manager ma) {
if (bonus < ma.bonus) return -1;
if (bonus > ma.bonus) return 1;
return 0;
}
}
class Employee implements Comparable<Employee> {
private String name;
private double salary;
public Employee(String n, double s) {
name = n;
salary = s;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
@Override
public int compareTo(Employee em) {
if (salary < em.salary) return -1;
if (salary > em.salary) return 1;
return 0;
}
}
@Override
public int compareTo(Employee ma) {
Manager m=(Manager)ma;
if (bonus < m.bonus) return -1;
if (bonus > m.bonus) return 1;
return 0;
}