Mike
Mike

Reputation: 14606

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. 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

Answers (2)

Mureinik
Mureinik

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

Mena
Mena

Reputation: 48424

No. Strings (and Integers) 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

Related Questions