字符串作为HashMap中的键 [英] String as a key in HashMap

查看:475
本文介绍了字符串作为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:

这篇关于字符串作为HashMap中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆