-1

I have hashset whare i will store set to objects and i want to find particular object, in this case why do i need to override the hashcode and equals method which i read from below example

public class Emp 
{
    private int age ;

    public Emp( int age )
    {
        super();
        this.age = age;
    }

    public int hashCode()
    {
        return age;
    }

    public boolean equals( Object obj )
    {
        boolean flag = false;
        Emp emp = ( Emp )obj;
        if( emp.age == age )
            flag = true;
        return flag;
    }
}

They are saying i would get false for the below query if i not override the hashcode and equals method.

System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp(25))--->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove( new Emp(24)--->>>"+hs.remove( new Emp(24));
System.out.println("Now HashSet Size--->>>"+hs.size());

I got confuse how this is related to hashcode and equals just checking the contains(anyobject) and remove(anyobject) in hashset .

Can somebody explain me the above scenario?

adithyan .p
  • 121
  • 1
  • 3
  • 12
  • 3
    Possible duplicate: https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java?rq=1 –  Jan 12 '17 at 05:52
  • Are you asking why you need to override either one of them, or why you need to override them both? If the latter: http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java – yshavit Jan 12 '17 at 05:54
  • 1
    How is the container supposed to know if it contains something if it can't tell whether any two things are equal or not? Likewise, how is it supposed to know if things are equal if you don't tell it how to do that? – azurefrog Jan 12 '17 at 05:55
  • 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.- Effective Java – Mustafa sabir Jan 12 '17 at 05:56
  • 2
    Possible duplicate of [Why do I need to override the equals and hashCode methods in Java?](http://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java) – abksrv Jan 12 '17 at 05:59

1 Answers1

4

At the base of your confusion is the concept of identity vs equality, and what does it mean for a set to contain an element. Let me try to explain.

Suppose in some place in your code you have done this:

HashSet<Emp> hs = new HashSet<>();
hs.add(new Emp(32));

In some other place, you want to see whether an employee for age 32 is in the set. How would you do it? You may consider this:

boolean isThere = hs.contains(new Emp(32));

what you're doing here is creating an instance of Emp passing 32 to the constructor, and then passing the instance to contain().

Note that this instance is not the same instance as the one you created when you added to the set. So, the question is: should contains() return true, as this instance is identical to the one you added, or should it return false, as it is not the very same instance?

The result depends on how hashCode() and equals() are implemented for Emp. With the default implementation, equals() returns true only if the instance passed is the very same that is contained (i.e. uses == to compare the instance passed to contains() and the one stored). In this case, it would return false.

To understand hashCode(), you need to understand how a HashSet works. When you add an element to a HashSet, an index in an array is computed from the element using hashCode() % <size of the array>. The element is then set as value at the corresponding index.

As different elements may end up having the same hashCode(), more elements may be mapped at the same index, in which case a list of collisions is maintained.

So, going back to your case, why do you need to implement hashCode()? because the default implementation will return different numbers for different instances of Ent, event though age may be the same (The implementation is JVM dependent, for example it could return the address in memory of the instance). So, for contain to work, we need to make sure that the same index in the array is computed for the two instances, hence you need to implement it accordingly. for example, in this case, hashCode() could return the age itself.

Roberto Attias
  • 1,883
  • 1
  • 11
  • 21