Java:通用方法和数字

2022-09-03 06:02:54

我想做一个泛型方法,使数字的总和。List

我正在尝试的是这个:

public static <T extends Number> T sumList(List<T> data)
{
    T total = 0;
    for (T elem : data)
    {
        total += elem;
    }
    return total;
}

但问题是那个和那个.there is no += operator in Ttotal can't be assigned to zero

我该怎么做?

谢谢


答案 1

有一些方法可以一起破解它,但老实说,泛型根本不是这里的方法。为每个具体的基元包装器类型生成一个方法,并单独实现它们。要让它变得通用太麻烦了。算术运算不能一般地发生。

你也不会通过使它变得通用而真正获得任何东西。它是如此简单和恒定的代码,你不必担心代码重复,因为它不会改变。而且人们不会将自己类型的Number传递给您的代码;它所适用的类型域已经很好地定义和有限。


答案 2

我最近已经这样做了(基于lambdaj代码),请注意,它需要所有元素都是相同的类型(你不能真正添加a和a),如果不是这种情况,可以抛出一个CCE,并且不会处理自定义:ByteBigDecimalNumber

public class SumAggregator<T extends Number> {
    public T aggregate(Iterable<T> iterable) {
        T result = null;
        for (T item : iterable) {
            result = aggregate(result, item);
        }
        return result;
    }


    @SuppressWarnings("unchecked")
    protected T aggregate(T first, T second) {
        if (first == null) {
            return second;
        } else if (second == null) {
            return first;
        } else if (first instanceof BigDecimal) {
            return (T) aggregate((BigDecimal) first, (BigDecimal) second);
        } else if (second instanceof BigInteger) {
            return (T) aggregate((BigInteger) first, (BigInteger) second);
        } else if (first instanceof Byte) {
            return (T) aggregate((Byte) first, (Byte) second);
        } else if (first instanceof Double) {
            return (T) aggregate((Double) first, (Double) second);
        } else if (first instanceof Float) {
            return (T) aggregate((Float) first, (Float) second);
        } else if (first instanceof Integer) {
            return (T) aggregate((Integer) first, (Integer) second);
        } else if (first instanceof Long) {
            return (T) aggregate((Long) first, (Long) second);
        } else if (first instanceof Short) {
            return (T) aggregate((Short) first, (Short) second);
        } else {
            throw new UnsupportedOperationException("SumAggregator only supports official subclasses of Number");
        }
    }

    private BigDecimal aggregate(BigDecimal first, BigDecimal second) {
        return first.add(second);
    }

    private BigInteger aggregate(BigInteger first, BigInteger second) {
        return first.add(second);
    }

    private Byte aggregate(Byte first, Byte second) {
        return (byte) (first + second);
    }

    private Double aggregate(Double first, Double second) {
        return first + second;
    }

    private Float aggregate(Float first, Float second) {
        return first + second;
    }

    private Integer aggregate(Integer first, Integer second) {
        return first + second;
    }

    private Long aggregate(Long first, Long second) {
        return first + second;
    }

    private Short aggregate(Short first, Short second) {
        return (short) (first + second);
    }
}

此代码在 ideone 上执行,并带有示例