Java: Java. Lang. Double Cannot Be Cast to Java. Lang. String
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...
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 ?
8 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.
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.
how about
mvalue = listMap.get("mvalue");
?
First of all, make a HashMap with Class Types defined , like : HashMap<String,Double>
Secondly , this should work :
mvalue = Double.parseDouble(Double.toString(listMap.get("mvalue")));
Although, best way is :
mvalue = listMap.get("mvalue");
// provided defined HashMap is HashMap<String,Double>
If you introduce generics you will immeditely discover the probblem
Map<String, Double> listMap = new HashMap<String, Double>();
Double mvalue = listMap.get("mvalue");
The reason is that your map does return a Double and not a String, hence the error message.
try this :
HashMap<String, Double> listMap = new HashMap<String, Double>();
Double mvalue = 0.0;
listMap.put("mvalue", mvalue);
mvalue = listMap.get("mvalue");
Your code should looks like:
Map<String,Double> listMap = new HashMap<String,Double>();
double mvalue = 0.0;
listMap.put("mvalue", mvalue );
mvalue = Double.parseDouble( String.valueOf(listMap.get("mvalue")) );
Notice that if you need to retrieve a wrapper and not a primitive type, you can use on wrapper classes XXX.valueOf() instead of XXX.parseXXX() which returns a primitive.
mvalue = Double.parseDouble(String.valueOf(listMap.get("mvalue")));