【发布时间】:2012-12-25 22:42:33
【问题描述】:
假设我们有 2 个有序的数字集合。我们要逐个元素地计算算术差异。 我认为我们需要使用数字列表来模拟“有序数字集合”的概念。 问题是没有为 Number 定义算术差异(如 3-2 中的平庸的“-”)。 我可以将所有内容都转换为 Double,但我更喜欢干净的解决方案。
public static <E extends Number> List<E> listDifferenceElementByElement(List<E> minuend, List<E> subtrahend) throws Exception {
if (minuend.size() != subtrahend.size()) {
throw new Exception("Collections must have the same size"); //TODO: better exception handling
}
List<E> difference = new ArrayList<E>();
int i = 0;
for (E currMinuend : minuend) {
difference.add(currMinuend-subtrahend.get(i)); //error: The operator - is undefined for the argument type(s) E, E
i++;
}
return difference;
}
有什么想法吗?
【问题讨论】:
-
为什么需要泛型类型?如果您将
E改为Double会怎样? -
假设我想要一些可以与任何数字类型(整数、浮点数、双精度...)一起使用并可能返回相同类型的东西
-
作为一个练习,你不能用简单的方式来做。实际上,它非常有用,因为如果您拥有这样的功能,将不会有太多收获。如果您关心性能,您可以改用
long[]或double[]。这是数学库中通常使用的。
标签: java list generics collections array-difference