Java: why equal method is not called when searching for same variable in hashmap
java
Solution
1) getHashCode is called one when you call put, then again when you call contains.
2) in the first case, the hashmap contains a reference to a, i.e. the address of a in memory, so there is no need to call equals. In the second case, the table lookup finds a, but this is a different object from the new A that you gave as a parameter, so there is a need to call equals() to find out if they are equal (they could be different and have the same hash code, this would be a collision).
Problem
Here is my test class.. ``` import java.util.HashMap; public class Test { public static void main(String[] args) { A a = new A(0, 1); HashMap<A, Integer> map = new HashMap<A, Integer>(); map.put(a, (a.x + a.y)); System.out.println(map.containsKey(a)); System.out.println("----------------- "); System.out.println(map.containsKey(new A(0, 1))); } } ``` and here is my class A with hashcode and equal method generated by eclipse. ``` class A { int x, y; public A(int x, int y) { super(); this.x = x; this.y = y; } @Override public int hashCode() { System.out.println(" in hashcode"); final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { System.out.println(" in equal"); if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; A other = (A) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } ``` The output of program is ``` in hashcode in hashcode true ----------------- in hashcode in equal true ``` My questions are: (I know the contract of hashcode and equal and why it is used) - Why in first case hashcode method is called twise ? - Why in first case equal does not called ? How JVM know that it is the same variable we are searching?