问题
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:
"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;
}
回答1:
Declare numbers as ArrayList<Integer> numbers.
Then the Integer will be unboxed to int. Right now, your arraylist contains objects that may not be ints.
For the moment, numbers.get() will return an object, and you can not add an object to an int directly.
You could always cast the element to Integer, but I would recommend the first option.
回答2:
// create a list
List<Integer> ints = Arrays.asList(1, 2, 3);
// get the sum of the elements in the list
int sum = MathUtils.sum(ints);
回答3:
As others have pointed out, you need to give your ArrayList a type. You can then use native streams to make the code a little more compact:
ArrayList<Integer> numbers = ... ;
numbers.stream().mapToInt(i -> i).sum();
回答4:
This will works fine.
import java.util.ArrayList;
public static int sumNumbers(ArrayList<Integer> numbers){
int sum = 0;
for(int i = 0; i<numbers.size(); i++){
sum+=numbers.get(i);
}
return sum;
}
Or
public static int sumNumbers(ArrayList<Integer> numbers){
return numbers.stream().mapToInt(n->n).sum();
}
来源:https://stackoverflow.com/questions/52874037/sum-of-the-elements-arraylist