What types of data types are admissible to use as keys in maps in java? Is it ok to use a double? How about a String?
6 Answers
Check out the API as there may be limitations on permissible types for keys depending on the specific map. Also, you can only use reference types but not primitive types. So double won't work, but Double is fine. Finally, the key should preferably not be mutable as this can cause aberrant behavior.
Comments
You can use any object type. But in order to get correct behavior the type has to have a hashCode() and equals() functions correctly implemented.
So if you want to use double you should instead use Double and because of boxing and unboxing you can actually pass double values to the functions like add() etc.
Comments
doubles won't work, as they are primitive type, that is, you cannot define a map Map<double,String>. However, you can define Map<Double,String> and then use a double value for the put method (thanks to autoboxing).
The caveat for abitary object in a map is, that unless the equal and hashcode methods are overridden, equality is based on references, which might not be the desired behavior. (So you might end up with two entries, where you would only expect one.)
Comments
For a key you can use any Object that is unique to your dataset. You cannot use int or double but you can use Integer or Double. Please note that a key can only have one value, hence the requirement for a object that is unique. If you add the same key twice only the second value will be stored in the Map