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?
containsKey() doesn't call equals()
Since the HashMap has the exact object that you're looking for, it doesn't need to call equals to verify that the object is the right one. When you get an object from a HashMap , first the hashCode is evaluated to find the right bucket.
HashMap containsKey() Method in Java util. HashMap. containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.
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.
JVM checks the hashcode bucket of that object's hashcode, if there are more objects with the same hashcode, then only, the equals() method will be executed. And, the developer should follow correct contract between the hashCode() and equals() methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With