开发者

Java - Data types used as keys in maps

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 St开发者_如何学Goring?


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.


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.


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.)


you must use an object
if you want to use double you can use the Double wrapper class you can't use primitive data type like int or long or double if you want to use one you can look for the wrapper class that represent it

String is okey since it's a Class


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


Primitive data types are not allowed, better you Wrapper class to store your data in map. Moreover, until and unless you override your equal and hashcode method, using map is of not much use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜