ohGosh
ohGosh

Reputation: 559

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 String?

Upvotes: 3

Views: 10389

Answers (6)

farooq.ind
farooq.ind

Reputation: 21

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.

Upvotes: 0

Ben
Ben

Reputation: 13635

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

Upvotes: 0

confucius
confucius

Reputation: 13327

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

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93050

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.

Upvotes: 3

Janick Bernet
Janick Bernet

Reputation: 21204

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

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 6

Related Questions