字符串作为HashMap中的键 [英] String as a key in HashMap
问题描述
我已经看到了,只有String被用作HashMap中的一个键。虽然put()方法将Object作为参数,但它的重要性如何。如果任何其他对象也可以用作Key?
请提供答案。
任何提供 hashCode )
是地图中完美的关键人物:请参阅理解equals和hashCode在HashMap中的工作方式。
另外,正如@Jon所说,映射中的所有键都应该是
编辑:当然,您需要实现 equals()
和 hashcode()
。我认为与其他问题链接的标题明确表示。但是 hashcode()
的愚蠢实现只会给你带来退化的 HashMap
,这表现很差。
编辑2:正如@Adrian在他的回答中提到的,泛型将帮助您限制地图的键和值的类型。
参考文献:
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:
- Effective Java Programming Language Guide, sample chapter about equals() and hashCode()
- Java theory and practice: Hashing it out
- Equals and HashCode
这篇关于字符串作为HashMap中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!