简体   繁体   English

如何为子类编写hashCode()

[英]How to write hashCode() for subClass

I have a question about hashCode. 我有一个关于hashCode的问题。 For example: 例如:

class A{
   String name;
   int age;

   @Override
   public int hashCode(){
       int hash = 0;
       hash = age;
       hash = 31*hash + name.hashCode();
   }
}
class B extends A{
}
class C extends A{
}    

My question is, if I instantiate one B object and one C object with the same name and age. 我的问题是,是否实例化具有相同名称和年龄的一个B对象和一个C对象。 Then the hashCode() for A and B are the same as well. 然后,A和B的hashCode()也相同。 Is it correct for hashCode()? hashCode()是否正确? if not, what should I do to modify my code? 如果没有,我该怎么做才能修改我的代码?

Sure, that's ok for hashCode() to do that. 当然,可以使用hashCode()做到这一点。

Of course, if B or C adds any new fields (which would be common), then they should override hashCode() , call super.hashCode() and "extend" the value as well. 当然,如果BC添加任何新字段(这是常见的),则它们应覆盖hashCode() ,调用super.hashCode()并“扩展”该值。

Also, as @bradimus hinted in a comment to question, when you override hashCode() , you should very likely also override equals() . 另外,正如@bradimus在对问题的评论中暗示的那样,当您覆盖hashCode() ,您很有可能也应该覆盖equals()

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

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