【发布时间】:2017-05-15 12:33:10
【问题描述】:
我有一个名为 Employee 的简单类。
public class Employee<T extends Number> {
private final String id;
private final String name;
private final T salary; //generic type salary
public Employee(String id,String name,T salary){
this.id = id;
this.name = name;
this.salary = salary;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public T getSalary() {
return salary;
}
}
在这里使用归约,我可以添加 Double 类型。但我需要添加泛型类型。工资中的值可以是 Double 或 Integer。那么有什么方法可以使用提供任何灵活性,以便我可以添加任何 Sub 类型的 Number。
public static void main(String[] args) {
//creates employee list and three employees in it
List < Employee > employees = new LinkedList < > ();
employees.add(new Employee("E001", "John", 30000.00));
employees.add(new Employee("E002", "Mark", 45000.00));
employees.add(new Employee("E003", "Tony", 55000.00));
employees.stream().map(Employee::getSalary).reduce(0, (a, b) -> {
//only able to add double type values, but i need any sub type of number
return a.doubleValue() + b.doubleValue();
});
}
Please help me.
【问题讨论】:
-
你得到什么错误?
-
我没有收到任何错误。我需要知道一种方法,这样我就可以添加整数或双精度数。 employees.stream().map(Employee::getSalary).reduce(0, (a, b) -> { //只能添加双精度类型的值,但我需要任何子类型的数字 return a.doubleValue() + b.doubleValue(); });在这里,我限制了加倍。我需要知道有什么方法可以消除这种限制并使用任何数字类型加法。
-
没有理智的程序员会使用
double值作为货币值。同样,抽象工资的存储和计算的实际类型的想法是没有意义的。它会无益地引起问题。 -
通过数字生成永远不会顺利。绝不。为整个程序选择一种数字类型并坚持下去。
标签: java generics java-8 java-stream