问题描述
嘿,我正在使用 HashMap
来跟踪公告板上的服务和服务请求.但是,我必须有哈希码和等于错误,因为我得到了重复的键.谁能告诉这可能是为什么?
Hey I'm using a HashMap
to keep track of services and service-requests on a BulletinBoard. However, I must have the hashcode and equals wrong because I'm getting duplicate keys. Can anyone tell why this might be?
keySet的内容:
以下是相关代码:
推荐答案
最可能的原因是您用作键的对象是可变的.因此,如果您执行以下操作:
The likeliest reason is that the objects you use as keys are mutable. So if you do something like:
地图的行为会出乎意料.
The behaviour of the map will be unexpected.
cf 地图的javadoc
注意:如果将可变对象用作映射键,则必须非常小心.如果对象的值以影响等于比较的方式更改,而对象是映射中的键,则不会指定映射的行为.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
这篇关于为什么我的 HashMap 允许重复键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!