I had seen, only the String is used as a key in HashMap.Although the put() method takes Object as a parameter.What is the significant of it.If any other object can also used as a Key or not? Please provide the answers.
Any object that provides a meaningful implementation of hashCode()
is a perfect key candidate in a map: see Understanding the workings of equals and hashCode in a HashMap.
Also, as @Jon mentioned, all keys in your map should be of the same type.
EDIT: Of course, you need to implement both equals()
and hashcode()
. I thought the title of the link to the other question made that clear. But a dumb implementation of hashcode()
will just bring you a degenerate HashMap
which performance is poor.
EDIT2: As @Adrian mentioned in his answer, generics will help you constrain the type of keys and values for the map.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With