【发布时间】:2016-10-28 10:00:03
【问题描述】:
这是一个主类Employee.java 和另外两个扩展主类的类。 ArrayList<Employee> 包含来自 createFixedEmployee.java 和 createPerHourEmployee 的对象。如何将ArrayList中的对象按薪水排序,如果某些对象的薪水相同,则按字母顺序对其名称进行排序?
我尝试使用Comparator.comparing(); 但不起作用,我收到错误Cannot resolve method getMonthSalary(); 这是代码:
createPerHourEmployee.java
public class createPerHourEmployee extends Employee {
private double salary;
public createPerHourEmployee() {}
public double getSalaryPerHour() { return this.salary; }
public double setSalaryPerHour(double value) {
return this.salary = value;
}
public createPerHourEmployee (int _id, String _name, double _salary) {
setEmployeeID(_id);
setEmployeeName(_name);
this.salary = _salary;
}
public double getMonthSalary() {
return salary * (20 * 0.8);
}
public String toString() {
return getEmployeeID() + ", " + getEmployeeName() + ", " + getSalaryPerHour();
}
}
createFixedEmployee.java
public class createFixedEmployee extends Employee {
private double salary;
public createFixedEmployee() {}
public double getSalaryFixed() {
return this.salary;
}
public double setSalaryFixed(double value) {
return this.salary = value;
}
public createFixedEmployee(int _id, String _name, double _salary) {
setEmployeeID(_id);
setEmployeeName(_name);
this.salary = _salary;
}
public double getMonthSalary() {
return this.salary;
}
public String toString() {
return getEmployeeID() + ", " + getEmployeeName() + ", " + getSalaryFixed();
}
}
Employee.java
import java.util.ArrayList;
import java.util.Comparator;
public abstract class Employee {
private int base_id;
private String base_name;
public int getEmployeeID () {
return this.base_id;
}
public int setEmployeeID (int value) {
return this.base_id = value;
}
public String getEmployeeName () {
return this.base_name;
}
public String setEmployeeName(String value) {
return this.base_name = value;
}
public abstract double getMonthSalary();
public static void main(String[] argc) {
ArrayList<Employee> Employee = new ArrayList<Employee>();
Employee.add(new createPerHourEmployee(1, "asd", 1300));
Employee.add(new createFixedEmployee(7, "asds", 14025));
Employee.add(new createPerHourEmployee(2, "nikan", 1230));
Employee.add(new createPerHourEmployee(3, "nikalo", 12330));
Employee.add(new createFixedEmployee(6, "aaaa", 14025));
Employee.add(new createFixedEmployee(4, "nikaq", 140210));
Employee.add(new createFixedEmployee(5, "nikas", 124000));
Employee.add(new createFixedEmployee(6, "nikab", 14025));
Employee.sort(Comparator.comparing(Employee::getMonthSalary)
.thenComparing(Employee::getEmployeeName)); // here is an error
}
}
所以我尝试过使用
Employee.sort(Comparator.comparing(createFixedEmployee::getMonthSalary).
thenComparing(createFixedEmployee::getEmployeeName));
效果很好,但我需要对所有类进行排序,而不仅仅是一个类。
【问题讨论】:
-
@Mureinik:我意识到这一点并在您发布的同时发布了答案。 :-)
-
@T.J.Crowder, Mureinik 哦,当然。我找不到这个问题..我会记下,谢谢
标签: java class sorting arraylist compiler-errors