Using Float Numbers for a Card Key

after creating a new object: Map<Float,Integer> m = new HashMap()<Float,Integer>;

I have an array with "float" numbers that are unique. I want to add these floating point numbers as m key ! can I do it like: m.put(new Float(a[i]),"cat"); ?

thanks

+4
source share
4 answers

I would recommend against using floating point numbers as hash map keys, if possible. Your keys should match exactly when you look at the values, and it's easy to get floating point numbers that aren't quite right.

+5
source

Just to take all the answers together.

  • The specified Map cannot accept strings, so you cannot say m.put (f, "cat")
  • You can, but don't have to wrap the float with Float: auto-boxing does this automatically, so you can just say m.put (a [i], "cat")
  • You are not recommended to use floating point types (Float and Double) as a map key. This can cause problems when trying to extract a value from the map using the get (key) method.
  • Note that the default type for floating constants is double, not float. Therefore, be careful with floats, use them only if you really need them. In either case, use the float modifier around constants such as 3.14f.
+2
source

You cannot do m.put(new Float(a[i]),"cat"); because the value must be Integer . To do this, you need to declare it as Map<Float,String> m = new HashMap()<Float,String>; .

0
source

Trim to a predetermined precision to generate predictable keys based on floating point numbers. JavaScript example

 const precision = Math.pow(10, 4); // where 4 is number of decimal places to retain const a = 12.5678912331; b = 13.75324122; c = 21.32112221 const key = '' + Math.floor(a * precision) + '_' + Math.floor(b * precision) + '_' + Math.floor(c * precision); const aMap = new Map(); aMap.set(key, 'some value'); 

Useless fact: this is taken from the code used to index vertices in three-dimensional objects. By setting lower accuracy, this allows you to combine nearby peaks.

0
source

All Articles