本文介绍了Java泛型和数字相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 java 中一般地添加数字.我遇到了困难,因为 Numbers 类并不真正支持我想做的事情.到目前为止我尝试过的是:
I would like to generically add numbers in java. I'm running into difficulty because the Numbers class doesn't really support what I want to do. What I've tried so far is this:
public class Summer<E extends Number> {
public E sumValue(List<E> objectsToSum) {
E total = (E) new Object();
for (E number : objectsToSum){
total += number;
}
return null;
}
显然这行不通.我怎样才能更正这个代码,以便我可以得到一个 或
或其他内容的列表并返回总和?
Obviously this will not work. How can I go about correcting this code so I could be given a list of <int>
or <long>
or whatever and return the sum?
推荐答案
为了通用地计算总和,您需要提供两个操作:
In order to calculate a sum generically, you need to provide two actions:
- 一种对零项求和的方法
- 对两个项目求和的方法
在 Java 中,您可以通过接口来实现.这是一个完整的例子:
In Java, you do it through an interface. Here is a complete example:
import java.util.*;
interface adder<T extends Number> {
T zero(); // Adding zero items
T add(T lhs, T rhs); // Adding two items
}
class CalcSum<T extends Number> {
// This is your method; it takes an adder now
public T sumValue(List<T> list, adder<T> adder) {
T total = adder.zero();
for (T n : list){
total = adder.add(total, n);
}
return total;
}
}
public class sum {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(4);
list.add(8);
CalcSum<Integer> calc = new CalcSum<Integer>();
// This is how you supply an implementation for integers
// through an anonymous implementation of an interface:
Integer total = calc.sumValue(list, new adder<Integer>() {
public Integer add(Integer a, Integer b) {
return a+b;
}
public Integer zero() {
return 0;
}
});
System.out.println(total);
}
}
这篇关于Java泛型和数字相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!