user1994657
user1994657

Reputation: 117

How to add a double value and a list element which is in double?

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.

Upvotes: 2

Views: 3003

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213203

You should always use Generic type for your Collections type like List, ArrayList, so on, when programming in Java 1.5+.

When you use a raw type List, then the method List.get(0) will always give you Object type, which you would need to do some casting to get it to work.

So, either you can add a casting to Double in your current code, which is absolutely a bad idea.

Or, you should use generic version of List as below: -

List<Double> list=new ArrayList<Double>();
list.add(1.1);

Note that, the value 1.1 is a double, still it can be added directly, without the need to convert it to Double. This is because of the feature of Java called Auto Boxing.

In Java, when you store a double value in a Double reference, then the double value is automatically boxed into Double. While in reverse case, it is called Unboxing, i.e. from Double to double.

That is why, when you do: -

temp+=list.get(0);

the value of list.get(0) is of type Double. And since you are performing an operation with double primitive type, that vlaue is automatically boxed to double, and addition operation is performed.

Upvotes: 3

Gothmog
Gothmog

Reputation: 891

You need to use the primitive wrapper class Double.

List<Double> list=new ArrayList<Double>();
list.add(new Double(1.1));

Upvotes: 4

fmsf
fmsf

Reputation: 37137

When you don't define the Generic Type. The list will return an object. Which means that you need to cast it:

temp+=(Double) list.get(0);

Though it is easier to just define the generic type directly in the declaration of the list:

List<Double> list=new ArrayList();

on a side note:

You need to use Double instead of double for this to work. Because double is a primitive type while Double is a java object that the list can store

Upvotes: 2

Related Questions