Java – string as key in HashMap

I have seen that only string is used as a key in HashMap Although the put () method takes object as an argument What is its importance If any other object can also be used as a key?

Solution

Any object that provides a meaningful hashcode () implementation is the perfect key candidate in the map: see understanding the workings of equals and hashcode in a HashMap

In addition, as @ Jon mentioned, all keys in the map should be of the same type

Edit: of course, you need to implement equals () and hashcode () I think the title of the link to another question is clear But a stupid implementation of hashcode () will only bring you a degraded HashMap with poor performance

Edit 2: as @ Adrian mentioned in his answer, generics will help you constrain the types of keys and values of the map

reference:

> Effective Java Programming Language Guide,sample chapter about equals() and hashCode() > Java theory and practice: Hashing it out > Equals and HashCode

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>