1

I am learning about hashcode() method in java. I was going through the tutorials and saw that hashcode() is mainly used in HashMap,HashTable and HashSet. This is what I have understood,If we want to insert an object as an key, then we have to override hashcode(). Other it wont be able to lookup for the key. I did a small example and I could achieve this without overriding the hashCode. So what is the exact use of hashCode() ?

See the code below

package hashcode;

public class Bucket {

    private int number;

    public void setNumber(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public String toString() {
        return "" + number;
    }

}


package hashcode;

import java.util.Hashtable;

public class MainHashcodeExample {

    public static void main(String[] args) {

        Hashtable<Bucket, String> map = new Hashtable<>();
        Bucket bucket = new Bucket();
        bucket.setNumber(100);
        map.put(bucket, "A");

        System.out.println(map.get(bucket));

    }
}
user414967
  • 5,225
  • 10
  • 40
  • 61

1 Answers1

2

You are using the exact same reference to your Bucket, so the default implementation of .hashCode() and .equals() are used (resp. System.identityHashCode() and reference equality).

Now try and:

Set<Bucket> set = new HashSet<>();

// Create two buckets b1, b2 with the same number

set.add(b1); set.add(b2);

The set will have size 2. If b1 and b2 were equal (which they are not), the set would have had size 1.

Now, let us suppose that you implement .equals(), but not .hashCode():

// no hashCode(), but...

@Override
// simplified
public boolean equals(@Nullable final Object obj)
{
    // instanceOf works with null, so this works
    if (!(obj instanceOf Bucket))
        return false;
    return ((Bucket) obj).number == number;
}

and you run the code above... The set will still have size 2. Why? Because b1 and b2 are not the same reference, and Object's .hashCode() will (most probably) return a different result for both.

You therefore need to override both .equals() and .hashCode() for proper use. See the javadoc of Object for more details, the contract for both is explained at length.

Note also that .hashCode() has no "cryptographic value". This is a perfectly legal (albeit useless) implementation of it:

@Override
public int hashCode()
{
    return 42;
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • yes. It is working fine after I overriden the equals and hashcode()method. so can we say hashcode is highly dependent on equals? – user414967 Oct 30 '14 at 09:51
  • They are both intrinsically linked; again, the javadoc for Object explains it all, I cannot recommend enough that you read it thoroughly ;) – fge Oct 30 '14 at 09:52