
Could you please explain me why equals and hashcode methods to override? and which implementations should override these methods? give me an example...

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.
Example:
import java.util.*;
public class HashTableExample{
public static void main (String args[]){
java.util.Hashtable hashtable = new java.util.Hashtable();
hashtable.put(new Entity(1), new Entity(1));
hashtable.put(new Entity(2), new Entity(2));
hashtable.put(new Entity(3), new Entity(3));
System.out.println("Size of hashtable is: "+hashtable.size());
}
}
class Entity{
int id;
Entity(int id) {this.id = id;}
public int hashCode() {
return id;}
public boolean equals(Object o) {
return true;
}
}
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.