Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Float numbers for the map's key

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

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

thanks

like image 490
user472221 Avatar asked Nov 20 '10 19:11

user472221


People also ask

Can you put float as a key in hash map?

I would recommend against using floating point numbers as hash map keys if possible. Your keys must match exactly when you look up values, and it's easy to get floating point numbers that aren't exactly right. That's why in these situations precision is being used i.e.

How do you get top 5 values on a map?

algorithm: Add first 5 values to an array, sort the array, iterate through the map until you find a value higher than the first value in the array (the lowest), replace the lowest, resort the array (in case the new value is higher than the others), continue.

Can double be the key of a map C++?

Using doubles as keys is not useful. As soon as you make any arithmetic on the keys you are not sure what exact values they have and hence cannot use them for indexing the map. The only sensible usage would be that the keys are constant.


2 Answers

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

like image 97
Adam Crume Avatar answered Oct 01 '22 08:10

Adam Crume


Just to take all answers together.

  1. The mentioned Map cannot accept strings, so you cannot say m.put(f, "cat")
  2. You can but do not have to wrap float using Float: auto-boxing does it for you automatically, so you can just say m.put(a[i],"cat")
  3. You are not recommended to use floating point types (Float and Double) as map key. It may cause problems when you try to extract value from map using get(key) method
  4. Note also that default type for floating constants is double, not float. So, be careful with floats, use them only if you really need them. In any case use float modifier near constants like 3.14f.
like image 37
AlexR Avatar answered Oct 01 '22 08:10

AlexR