我有一个名为 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 类型。但我需要通用类型添加。 salary 中的值可以是 Double 或 Integer。那么有没有什么方法可以提供任何灵 active ,以便我可以添加任何子类型的数字。
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.
最佳答案
我建议您首先在变量声明中添加正确的泛型类型参数:
List<Employee<Double>> employees = new LinkedList<>(); // you need to add "<>"s here
employees.add(new Employee<>("E001", "John", 30000.00));
employees.add(new Employee<>("E002", "Mark", 45000.00));
employees.add(new Employee<>("E003", "Tony", 55000.00));
然后,这将返回一个可转换为Number
的double
,并且Number
可以转换为int
、float
、short
等:
Number num = employees.stream().map(Employee::getSalary).reduce(0.0, (a, b) -> {
return a + b;
});
或者,摆脱泛型。不使用 T
,而是使用 Number
作为工资类型。
class Employee {
private final String id;
private final String name;
private final Number salary; //generic type salary
public Employee(String id,String name,Number salary){
this.id = id;
this.name = name;
this.salary = salary;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public Number getSalary() {
return salary;
}
}
关于java - 我想添加通用类型编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43979705/