Integer cannot be cast into Float?

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

Thanks for helping, Aaron.

1 Like

Hi Aaron,

Try to first store the value in a int variable and then cast that variable.

It worked for me in the past.

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.

I think it’s because you return an Object type.

If you want to return float, you need to write:
HashMap<String, Float>

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");

2 Likes

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.

There are many ways to represent the value 0 as a float in Processing: :wink:
0.0, 0., .0, 0f, 0e0, (float) 0, 0*PI, etc.

1 Like