Why override Equals and HashCode methods?

Essentially 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 nodes. Here, to find out whether nodes collection contains a node with value 'A' you can use a simple `for` loop:

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;
}

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.

Credits: StackOverflow: Overriding equals and HashCode