元素总和ArrayList [英] Sum of the elements ArrayList
问题描述
我是Java的初学者,正在尝试获取ArrayList中所有元素的总和.我通过使用方法来执行此操作,并在该方法中得到此错误:
Im a beginner in Java and trying to get the sum of all the elements in the ArrayList. Im doing it by using a method and get this error in the method:
二进制操作数"+"的错误操作数类型,第一种类型:int,第二种 类型:对象"
"bad operand types for binary operatpr '+' first type: int, second type: Object"
我不知道我在做什么错,谢谢您的帮助!
I don't know what I'm doing wrong here, appreciate any help!
public static int sumNumbers(ArrayList numbers){
int sum = 0;
for(int i = 0; i<numbers.size(); i++){
sum+=numbers.get(i);
}
return sum;
}
推荐答案
将numbers
声明为ArrayList<Integer> numbers
.
然后Integer
将被取消装箱到int
.现在,您的arraylist
包含的objects
可能不是int
s.
Declare numbers
as ArrayList<Integer> numbers
.
Then the Integer
will be unboxed to int
. Right now, your arraylist
contains objects
that may not be int
s.
目前,numbers.get()
将返回object
,并且您不能直接将object
添加到int
.
For the moment, numbers.get()
will return an object
, and you can not add an object
to an int
directly.
您始终可以将元素强制转换为Integer
,但我建议使用第一个选项.
You could always cast the element to Integer
, but I would recommend the first option.
这篇关于元素总和ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!