Java: java.lang.Double cannot be passed to java.lang.String
I am storing double value inside HashMap as shown
HashMap listMap = new HashMap();
double mvalue =0.0;
listMap.put("mvalue",mvalue );
Now when I tried to extract this value as shown
mvalue = Double.parseDouble((String) listMap.get("mvalue"));
I am getting an error like
java.lang.Double cannot be added to java.lang.String
I'm confused here,
This is my actual HashMap and I am setting 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);
Can someone please tell me how the structure of the HashMap should look like?
You put Double on the card. Don't overlay on String first. This will work:
HashMap<String, Double> listMap = new HashMap<String, Double>();
mvalue = listMap.get("mvalue");
Your primitive twin is self-contained with a double object. Use Generics to avoid having to throw, that's part <String, Double>
.
If you introduce generics, you will immediately find the problem
Map<String, Double> listMap = new HashMap<String, Double>();
Double mvalue = listMap.get("mvalue");
The reason is that your card is returning Double
, and not String
therefore an error message.
What about
mvalue = listMap.get("mvalue");
?
I am assuming that your card will store many different types. Therefore I recommend 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 give you a double object, cast it to Double, and convert it to a string into a new variable.
First of all, create a HashMap with specific class types, for example: HashMap<String,Double>
Second, this should work:
mvalue = Double.parseDouble(Double.toString(listMap.get("mvalue")));
Although, the best way is:
mvalue = listMap.get("mvalue");
// provided defined HashMap is HashMap<String,Double>
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 look like this:
Map<String,Double> listMap = new HashMap<String,Double>();
double mvalue = 0.0;
listMap.put("mvalue", mvalue );
mvalue = Double.parseDouble( String.valueOf(listMap.get("mvalue")) );
Note that if you need to get a wrapper rather than a primitive type, you can use XXX.valueOf () on wrapper classes instead of XXX.parseXXX (), which returns a primitive.
mvalue = Double.parseDouble(String.valueOf(listMap.get("mvalue")));