Jaikrat
Jaikrat

Reputation: 1154

hashCode implementation

class A{

      @Override
      public int hashCode() {
        return 10;
    }
}

public class SampleClass {

    public static void main(String[] args){
        Map map = new HashMap();

        map.put(new A(), "A");
        map.put(new A(), "B");

        System.out.println(map.size());

        System.out.println(new A().hashCode());
        System.out.println(new A().hashCode());
    }
}

Output :-

2

10

10

Why 2???. If we are implementing hashCode method which is returning same integer. Should not the size be 1???

Upvotes: 0

Views: 1006

Answers (2)

Vicente Plata
Vicente Plata

Reputation: 3380

From http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode()

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

Thus, when it comes to knowing if two objects are equal, equals is the way to go as Louis pointed out. Hashcode only tells where/how to store your objects given a hash-based collection implementation.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198014

You haven't overriden equals(Object), so they don't compare as equal.

Just because two objects have the same hash code doesn't mean HashMap assumes they're the same -- indeed, if that was the case, that would be really, really bad.

If you want two A objects to be treated as equal by HashMap, you must override equals(Object) in A to define one A as equal to another.

Upvotes: 9

Related Questions