Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



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

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


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


send me code


Advertisement
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 Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com