0
class Hash {
  int a;

  Hash(int h){
    a=h;
  }

  public boolean equals(Object o) {     
    Boolean h=super.equals(o);
    System.out.println("Inside equals ");
    return h;
  }

  public int hashCode() {    
    System.out.println("Inside Hash");    
    return 2;
  }    
}

public class Eq {    
  public static void main(String...r) {    
    HashMap<Hash,Integer> map=new HashMap<Hash,Integer>();    
    Hash j=new Hash(2);    
    map.put(j,1);
    map.put(j,2);
    System.out.println(map.size());
  }
}

output was

inside hash

inside hash
1

Since it returns the same hashcode , the second time an object is added in hashmap it must use the equals method but it doesnt call . So wats the problem here?

Bhushan
  • 18,329
  • 31
  • 104
  • 137
Prabhu
  • 11
  • 1

3 Answers3

7

The HashMap is testing with == before .equals, and since you are putting the same object twice, the first test passes. Try with:

    Hash j=new Hash(2);
    Hash k=new Hash(2);
    map.put(j,1);
    map.put(k,2);
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
0

The equality check is done by HashMap in three steps:

  1. hash code is different => unequal
  2. objects are identical (==) => equal
  3. equal method gives true => equal

The second step prevents calling equals since identical objects are always assumed equal.

Howard
  • 38,639
  • 9
  • 64
  • 83
-3

From the doc

put(): Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.

BlueDog
  • 966
  • 8
  • 15
  • The "specified key" is the hashcode, isn't it? Since the key is already used at the time of the second put, there is no need to check for equality hence no equals() call. Or did I mess it up? – BlueDog Jul 10 '11 at 13:52
  • The correct answer is the first one - there is a link to the hashmap code. – Petar Minchev Jul 10 '11 at 13:55
  • HashMap supports key collisions by creating an internal list containing all items with a specific hashcode. On a put, it searches all items with the same hashcode and uses == || .equals to make the final determination. so in the original question, it's hitting the hashCode, but the == comaprison is succeeding and short-circuitng the call to .equals. – g051051 Jul 10 '11 at 13:58