[英]Should I override equals() and hashCode() for String key in HashMap, Java?
I'm using HashMap<String, MySuperClass>
collection, where the key is in String
format.我正在使用HashMap<String, MySuperClass>
集合,其中的键是String
格式。 In general, in order to use HashMap
collection, it's necessary to override equals()
and hashCode()
.一般来说,为了使用HashMap
集合,需要覆盖equals()
和hashCode()
。
I want to clarify, should I override equals()
and hashCode()
for String
, Integer
, and other «primitive» classes in HashMap
?我想澄清一下,我应该为String
、 Integer
和HashMap
其他“原始”类覆盖equals()
和hashCode()
吗?
不。 String
s(和Integer
s)已经实现了equals
和hashCode
,并且您无法为它们覆盖它,因为这些类是final
,因此不可扩展。
When you use a class as a key for a HashMap
(or HashSet
, or Hashtable
for that matter), you should make sure it overrides hashCode()
and equals(Object)
.当您使用类作为HashMap
(或HashSet
或Hashtable
)的键时,您应该确保它覆盖hashCode()
和equals(Object)
。 The JDK's String
, the primitive wrappers (such as Integer
, Long
, etc.) and many others already do this for you, so you don't need to worry about it. JDK 的String
、原始包装器(例如Integer
、 Long
等)和许多其他包装器已经为您完成了这项工作,因此您无需担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.