Hi everyone, I have a “Node” class which contains an ‘attributes’ variable. The variable contains a variety of data types associated with a String key. I’m using a HashMap to implement it.
However, when I try and retrieve a float attribute and cast it to a float (this seems to work for PVectors, custom Node classes, boolean, but not floats), Java gives an error that “java.lang.Integer cannot be cast to java.lang.Float”.
Attached is a 5 line code written to demonstrate the problem:
// Create a HashMap which stores attributes which can consist of different data types.
HashMap<String, Object> attributes = new HashMap<String, Object>();
// Example usage (first one is the problem)
attributes.put("dist", 0);
attributes.put("visited", true);
// Print statement is necessary for error to show
float dist = (float)attributes.get("dist");
println(dist);
// Output - ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
Would the value be rounded up if I stored it as an int variable? I still require some decimals. I tried storing the value as an int variable by casting it into an int first, but now the variable cannot be cast into a float still. I’m only less than a week old to Java, so I might be missing something obvious, however I couldn’t find anything on Integer to Float errors for Java on google.
The 0 in attributes.put("dist", 0); becomes an Integer.
Use 0.0 instead, so it is stored as a Float: attributes.put("dist", 0.0);
Otherwise, use (Integer) as cast: float dist = (Integer) attributes.get("dist");
Aha, that worked, thank you to both of you! atttributes.put("dist", 0f) worked for me. I’ll probably stick to the first method, because the second method produces an error if I try to initialize a float value.