简体   繁体   English

我应该在 HashMap,Java 中为 String 键覆盖 equals() 和 hashCode() 吗?

[英]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 ?我想澄清一下,我应该为StringIntegerHashMap其他“原始”类覆盖equals()hashCode()吗?

不。 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) .当您使用类作为HashMap (或HashSetHashtable )的键时,您应该确保它覆盖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 、原始包装器(例如IntegerLong等)和许多其他包装器已经为您完成了这项工作,因此您无需担心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对于 HashMap,我应该覆盖键或值的 hashCode 吗? - For HashMap, should I override hashCode for key or value? Java集合:如果Hashmap的键是Immutable Object,那么我们是否需要重写哈希码和等于? - Java Collections: IF the key of Hashmap is Immutable Object then do we need to override hashcode and equals? HashMap使用override equals和hashCode不起作用 - HashMap with override equals and hashCode not working 当我覆盖equals()方法时,为什么要覆盖hashCode()? - Why should I override hashCode() when I override equals() method? 有效的Java:如果我创建的对象永远不会相互比较,我应该覆盖equals()和hashCode()吗? - Effective Java: should I override equals() and hashCode() if the objects I'm creating are never compared with each other? 如果我覆盖Java中的'equals'方法,为什么需要重写hashcode? - Why is there a need to override hashcode if I override the 'equals' method in Java? 我应该总是覆盖 equals、hashcode 和 toString 方法吗? - Should I always override equals, hashcode and toString methods? 为什么我应该重写equals和hashcode方法来跟随scnerio - why should I override equals and hashcode method for following scnerio 如果我重写.equals(),即使我不使用HashMap,也需要重写.hashCode()吗? - If I override .equals(), do I need to override .hashCode() even if I don't use a HashMap? 为什么我需要覆盖 Java 中的 equals 和 hashCode 方法? - Why do I need to override the equals and hashCode methods in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM