问题描述
我想要一个计算Integer,Double和Float类型的LinkedList的平均值的方法。
问题在于 sum + = i; 语句,因为java说+操作符没有定义对于类型的对象。
我可以进行强制转换,但是如果LinkedList的类型是Float,并且强制转换为Integer,那么我将不计算正确的意思。
我该怎么办?
public double mean(LinkedList<?> l)
{
double sum = 0 ;
int n = 0;
for(Object i:l)
{
n ++;
sum + = i;
}
return sum / n;
}
秒。这是 Integer , Float , Double的共同超类和其他数字类型。它没有定义操作符,只有转换方法到 double ,但这对您来说已经足够了:
public double mean (LinkedList<?extends Number> 1)
{
double sum = 0;
int n = 0;
for(Number i:l)
{
n ++;
sum + = i.doubleValue();
}
return sum / n;
}
I want to have a method which calculates the mean of a LinkedList of type Integer, Double and Float.
The problem is the sum += i; statement, since java says that the + operator isn't defined for type Object.
I could do a cast, but if the LinkedList was of type Float, for example, and the cast was to Integer, I would be not computing the correct mean.
What should I do? Thanks.
public double mean (LinkedList<?> l) { double sum = 0; int n = 0; for (Object i : l) { n++; sum += i; } return sum / n; }
You should restrict your list to Numbers. That is the common superclass for Integer, Float, Double and other numeric types. It has no operators defined, only conversion methods to e.g. double, but that is enough for you here:
public double mean (LinkedList<? extends Number> l) { double sum = 0; int n = 0; for (Number i : l) { n++; sum += i.doubleValue(); } return sum / n; }
这篇关于简单的Java泛型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!