user1077685
user1077685

Reputation:

Syntax error--passing "double" as primitive type to map

So I found source code that presumably parses a mathematical expression and calculates the answer. However, the code contains a syntax error when declaring a new map. This new map is supposed to hold a String and a number. I do know that maps can't reference primitive types, like double, though. How can I resolve this issue?

private Map<String, double=""> user_var = new HashMap<String, double="">();

To see the rest of the code, one can visit here

Thank you

Upvotes: 0

Views: 223

Answers (5)

Pshemo
Pshemo

Reputation: 124255

Use Map<String, Double> map = new HashMap<String, Double>();

Thanks to autoboxing you can use it like

map.put("one",1d);
double d = map.get("one");

Upvotes: 1

Haile
Haile

Reputation: 3180

Java has wrapper classes that allow you to use a primitive type where an Object is required. The wrapper class for the primitive type double is named Double. See here for details.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533590

You could use TObjectDoubleHashMap with allows a String key and a double value.

Upvotes: 2

Keppil
Keppil

Reputation: 46219

A Map can't contain a primitive of any kind. You can create one using the wrapper class for double though:

private Map<String, Double> user_var = new HashMap<String, Double>();

This can then be used (almost) exactly as if it contained doubles:

double value = 2.3;
user_var.put("myVar", value);

Upvotes: 1

Andrew Logvinov
Andrew Logvinov

Reputation: 21831

That's an incorrect declaration. Correct would be:

private Map<String, Double> user_var = new HashMap<String, Double>();

Upvotes: 2

Related Questions