1. 程式人生 > >String有重寫Object的hashcode和toString嗎?重寫equals不重寫hashCode會有什麼問題?

String有重寫Object的hashcode和toString嗎?重寫equals不重寫hashCode會有什麼問題?

String有重寫Object的hashCode和toString嗎:

  • String重寫了Object的hashcode和toString方法。

如果重寫equals不重寫hashCode會出現什麼問題:

  • 首先hashCode和equals應該滿足如下關係:
    1. 當object1.equals(object2)為true時,那麼object1.hashCode()==object2.hashCode()也要為true。
    2. 當object1.hashCode()==object2.hashCode()為false時,object1.equals(object2)也要為false。
    3. 當object1.hashCode()==object2.hashCode()為true時,object1.equals(object2)可能為true,也可能為false。
  • 如果重寫equals不重寫hashCode會出現什麼問題:
    • 在使用雜湊集合時,如HashSet,HashSet不能儲存重複的元素。如果重寫equals而不重寫hashCode會遇到如下情況,雖然object1.equals(object2),但object1.hashCode()==object2.hashCode()為false,導致HashSet仍然會將這兩個equals為true的元素都存入HashSet中,依據hashCode的值存到不同的位置。這樣子會產生問題。