java - 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'
解决方案
它与 Unboxed Type 和 Box Type 相关。
有关更多详细信息,请参阅此处:说类型是“盒装”是什么意思?
要使您的代码正常工作,只需将 Number 转换为 double 并求和即可。
Number num = myarraylist.get(i);
average += num == null ? 0 : num.doubleValue();
推荐阅读
- java - 如何显示进度条?多线程java
- unity3d - 何时以及为什么不应该使用预制变体?
- c++-cx - C ++中事件的目的是什么?
- erlang - 创建仅二进制的 Erlang 版本
- c# - ScreenPointtoRay 为鼠标跟随脚本创建问题
- oracle - Oracle Sql Developer 中的连接
- google-apps-script - 如何在 Google App Script 中为文件设置密码?
- android - 如何在标签布局中实现插页式广告?
- react-native - 如何将 this.props 数据放入 headerRight 选择器?
- python - python如何使用for循环打印出字符串中的元音