bad operand types for binary operator '+'
first type: int
second type: Object
This is saying: "You can't use the +
operator with one these two types" - and I bet you can guess which one - Object
- which, if you think about it, makes sense:
Remember that every class of every type you'll ever work with in Java extends Object
. So, when you're working with something that has been cast to Object
, Java knows almost nothing about what that something is. In particular, it would have no freaking clue what to do with a +
applied to one.
For instance, imagine that you had a Person
class and did
Person a = new Person();
Person b = new Person();
a + b; //WTF??
Would that make sense? Of course not.
Now, you might say "but I didn't add Objects to my list, I added Integers/Doubles/some other type that the + operator should work with" - and I'm sure you would be right, but the problem is that you added them to a List of Objects, which you created as such right here:
List sum toFeeBillListTot = new LinkedList();
When you do this, you're creating an "untyped list". This means you can add objects of any type you like to it - which might sound nice, but as a natural consequence, you can only retrieve Object
s from it, which is what you're doing now.
By "use a generic collection", @Jeroen is suggesting you do this instead:
List<Integer> toFeeBillListTot = new LinkedList<>();
Rather than creating a list of Objects, the <Integer>
means you're creating a list of integers, which means you can only add Integer
s to it, and also that every element you pull out of it will be an Integer, so you can do:
int sum = 0;
for (Integer sumItem : toFeeBillListTot) {
sum += sumItem;
}