Saturday, December 7, 2013

Recently I read through this Developer Works Document. The document is all about defininghashCode() and equals() effectively and correctly, but I am not able to figure out why we need to override these two methods.
How can I take the decision to implement these method efficiently?
share|improve this question
add comment

13 Answers

up vote75down voteaccepted
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. Let's analyze what whould happen if we override one but not the other and we attempt to use a Map.
Say we have a class like this and that two objects of MyClass are equal if their importantField is equal (with hashCode and equals generated by eclipse)
public class MyClass {

    private final String importantField;
    private final String anotherField;

    public MyClass(final String equalField, final String anotherField) {
        this.importantField = equalField;
        this.anotherField = anotherField;
    }

    public String getEqualField() {
        return importantField;
    }

    public String getAnotherField() {
        return anotherField;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((importantField == null) ? 0 : importantField.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final MyClass other = (MyClass) obj;
        if (importantField == null) {
            if (other.importantField != null)
                return false;
        } else if (!importantField.equals(other.importantField))
            return false;
        return true;
    }

}

Override only hashCode
Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you callmyMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition).
But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.
Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket. So, although they are equal, as they don't hash to the same bucket (different hashCode) the map can't realize it and both of them stay in the map.
Hope it was clear
share|improve this answer
 
Thanks for a nice explanation. –  Code Enthusiastic Jul 25 at 17:15 
add comment
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

   from Effective Java, by Joshua Bloch
By defining equals() and hashCode() consistently, you can improve the usability of your classes as keys in hash-based collections. As the API doc for hashCode explains: "This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable."
The best answer to your question about how to implement these methods efficiently is suggesting you to read Chapter 3 of Effective Java.
share|improve this answer
add comment

No comments: