Home Answers Viewqa Java-Interview-Questions how to override the hashCode() method ? and What is the advantage of overide the hashcode().

 
 


Hazarathaiah
how to override the hashCode() method ? and What is the advantage of overide the hashcode().
1 Answer(s)      a year and 4 months ago
Posted in : Java Interview Questions

send me code

View Answers

January 24, 2012 at 4:32 PM


It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them.

   @Override
   public int hashCode() {
       final int PRIME = 31;
       int result = 1;
       result = PRIME * result + number;
       return result;
   }
       @Override
       public boolean equals(Object obj) {
       if (this == obj)
           return true;
       if (obj == null)
           return false;
       if (getClass() != obj.getClass())
           return false;
       final Scrap other = (Scrap) obj;
       if (number != other.number)
           return false;
       return true;
   }

If you do not override them you have to use the default implentation in Object.









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.