Reputation: 14606
I'm using HashMap<String, MySuperClass>
collection, where the key is in String
format. In general, in order to use HashMap
collection, it's necessary to override equals()
and hashCode()
.
I want to clarify, should I override equals()
and hashCode()
for String
, Integer
, and other «primitive» classes in HashMap
?
Upvotes: 2
Views: 1416
Reputation: 311798
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)
. 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.
Upvotes: 5
Reputation: 48424
No. String
s (and Integer
s) already implement equals
and hashCode
, and there's no way you can override it for them since those classes are final
, hence not extensible.
Upvotes: 11