简体   繁体   中英

How to write hashCode() for subClass

I have a question about 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. Then the hashCode() for A and B are the same as well. Is it correct for hashCode()? if not, what should I do to modify my code?

Sure, that's ok for hashCode() to do that.

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.

Also, as @bradimus hinted in a comment to question, when you override hashCode() , you should very likely also override equals() .

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