how to override the hashCode() method ? and What is the advantage of overide the hashcode().

how to override the hashCode() method ? and What is the advantage of overide the hashcode().

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

Ads