javahashmapequalscontainskey

Java HashMap.containsKey() doesn't call equals()


I have a hashmap:

Map<LotWaferBean, File> hm = new HashMap<LotWaferBean, File>();

LotWaferBean lw = new LotWaferBean();
... //populate lw
if (!hm.containsKey((LotWaferBean) lw)) {
  hm.put(lw, triggerFiles[l]);
}

The code for LotWaferBean:

@Override
public boolean equals(Object o) {
        if (!(o instanceof LotWaferBean)) {
              return false;
        }
        if (((LotWaferBean) o).getLotId().equals(lotId)
                    && ((LotWaferBean) o).getWaferNo() == waferNo) {
              return true;
        }
        return false;
  }

In my IDE I put breakpoints in equals() but it is never executed. Why?


Solution

  • Try putting a breakpoint in hashCode().

    If the hashCode() of two objects in a map return the same number, then equals will be called to determine if they're really equal.