我想一般地在java中添加数字。我遇到了麻烦,因为Numbers类并不真正支持我想做的事情。到目前为止,我尝试过的是:
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; }
显然这是行不通的。我该如何更正此代码,以便获得<int>或列表,或<long>返回任何值?
<int>
<long>
为了一般地计算总和,您需要提供两个操作:
在Java中,您可以通过接口进行操作。这是一个完整的示例:
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); } }