I tried a code
double temp=0;
List list=new ArrayList();
list.add(1.1);
temp+=list.get(0); //error occurs here
Error that occurred is as follows
bad operand types for binary operator ‘+’
first type: double
second type: Object
What should I do to add the temp value and the double value in the list?
The programming language that I preferred is Java.
You should always use
Generic typefor yourCollectionstype likeList,ArrayList, so on, when programming inJava 1.5+.When you use a
raw typeList, then the methodList.get(0)will always give youObjecttype, which you would need to do some casting to get it to work.So, either you can add a casting to
Doublein your current code, which is absolutely a bad idea.Or, you should use
genericversion of List as below: –Note that, the value
1.1is adouble, still it can be added directly, without the need to convert it toDouble. This is because of the feature ofJavacalledAuto Boxing.In Java, when you store a
doublevalue in aDoublereference, then thedoublevalue is automatically boxed intoDouble. While in reverse case, it is calledUnboxing, i.e. fromDoubletodouble.That is why, when you do: –
the value of
list.get(0)is of typeDouble. And since you are performing an operation withdoubleprimitive type, that vlaue is automaticallyboxedtodouble, and addition operation is performed.