首页 > 解决方案 > How to find the average of numbers in a generic class of Numbers in Java?

问题描述

I have created a generic class that creates an ArrayList of Numbers

public class MyMathClass<T extends Number> {
private ArrayList<T> myarraylist;

public MyMathClass(ArrayList<T> arrayList){
    myarraylist = arrayList;
}

I tried to create a method that basically calculates the average of the given ArrayList

public double average(){
    var average = 0;
    for(int i = 0 ; i <= myarraylist.size(); i++){
        average += myarraylist.get(i);
    }
}

but when try to add the average with the value at index i, I get this error: "operator + cannot be applied to 'int' , 'T'

标签: javaoop

解决方案


它与 Unboxed Type 和 Box Type 相关。

有关更多详细信息,请参阅此处:说类型是“盒装”是什么意思?

要使您的代码正常工作,只需将 Number 转换为 double 并求和即可。

Number num = myarraylist.get(i);
average += num == null ? 0 : num.doubleValue();

推荐阅读