Search code examples
javahashmapguavaequalshashcode

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?


Solution

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