Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : java.lang.Double cannot be cast to java.lang.String

Tags:

java

I am storing a double value inside the a HashMap as shown

HashMap listMap = new HashMap();

double mvalue =0.0;

listMap.put("mvalue",mvalue );

Now when i tried to retrieve that value , as shown

mvalue = Double.parseDouble((String) listMap.get("mvalue"));

i am getting an error as

java.lang.Double cannot be cast to java.lang.String

I am confused here ,

This is my actual HashMap and i am setting the values in it as shown

HashMap listMap = new HashMap();
double mvalue =0.0 ;
List<Bag> bagList = null; 
listMap.put("bagItems",bagList);
listMap.put("mvalue", mvalue);

Could anybody please tell me , how the structure of the HashMap should be ?

like image 948
Pawan Avatar asked Mar 06 '12 11:03

Pawan


2 Answers

You have put a Double in the Map. Don't cast to String first. This will work:

HashMap<String, Double> listMap = new HashMap<String, Double>();
mvalue = listMap.get("mvalue");

Your primitive double is being Autoboxed to a Double Object. Use Generics to avoid the need to cast, which is the <String, Double> part.

like image 121
planetjones Avatar answered Sep 27 '22 20:09

planetjones


I guess your map will store many diferents types So I recomend <String, Object> generic

HashMap listMap = new HashMap<String, Object>();
double mvalue =0.0;
listMap.put("mvalue",mvalue );
.
.
.
String mValueString = Double.toString((Double) listMap.get("mvalue"));

This will get you the double object, cast it to Double, and the convert into string in new variable.

like image 22
TulioPa Avatar answered Sep 27 '22 19:09

TulioPa