Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
Will Sumekar Avatar asked Jan 06 '11 04:01

Will Sumekar


People also ask

Does containsKey use equals?

containsKey() doesn't call equals()

Does HashMap call equal?

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.

What is containsKey in HashMap Java?

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.

When equals method is called in HashMap?

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.


2 Answers

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.

like image 189
LazyCubicleMonkey Avatar answered Sep 18 '22 19:09

LazyCubicleMonkey


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.

like image 25
Abimaran Kugathasan Avatar answered Sep 18 '22 19:09

Abimaran Kugathasan