While creating a HashSet of your own class, always ensure that the HashCode() method of the key of HashSet doesn’t change. Java Object hashCode() is a native method and returns the integer hash code value of the object. If two objects are equal according to the equals() method, then their hash code must be the same. If two objects are unequal according to the equals() method, their hash codes are not required to be different.
public boolean equals (Object obj) // This method checks if some other Object // passed to it as an argument is equal to // the Object on which it is invoked.
public int hashCode() // This method returns the hash code value // for the object on which this method is invoked.
Whenever it(hashcode) is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
Below is the implementation of the above problem statement:
cam 451 sam 452
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.