简体   繁体   中英

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 ?

不。 String s(和Integer s)已经实现了equalshashCode ,并且您无法为它们覆盖它,因为这些类是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) . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM