Why override Equals and HashCode methods?
08 Feb 2014Essentially this post is about comparing two objects by their hashCode
or actual content
.
Question: How to find whether a collection of objects contains an object with a specific field value?
Let’s say you have a class Node
with a field name
and a collection of these nodes, List
for(Node node : nodes)
{
if(node.name == newNode.name)
{
return true;
}
}
Though it will work great, but there is a better way which is more efficient and can handle advanced cases like you have to check for 2 or more properties. By overriding HashCode and Equals method.
public class Node {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + name; // Note: name added
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Node)) {
return false;
}
Node other = (Node) obj;
if (name != other.name) {
return false;
}
return true;
}
public char name;
}
- HashCode for two objects should be same only if
equals()
method return true for both objects. - To check if an object is an instance of a particular class, use
instanceOf
orgetClass()
methods. Preferable getClass() because it checks for only same class unlike instanceof which checks subclass too.
Tip: You don’t need to write whole overridden methods code, rather you can use eclipse auto generator tools. Right click anywhere in your class, and go to Source > Generate hashCode() and equals(). Select properties which equals method should compare and hit done.