3

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 6

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1

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

0

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.