Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String as a key in HashMap

Tags:

java

hashmap

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.

like image 267
user230621 Avatar asked Nov 29 '22 06:11

user230621


1 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:

  • Effective Java Programming Language Guide, sample chapter about equals() and hashCode()
  • Java theory and practice: Hashing it out
  • Equals and HashCode
like image 113
Gregory Pakosz Avatar answered Dec 05 '22 08:12

Gregory Pakosz