Why does HashMap.put both compare hashes and test equality?

前端 未结 3 1932
灰色年华
灰色年华 2021-01-18 02:21

I analyse the HashMap source code in Java and get a question about the put method.

Below is the put method in JDK1.6:

3条回答
  •  萌比男神i
    2021-01-18 02:42

    It's just avoiding a method call when it can: If the hash (which isn't hashCode(), it's the map's own hashing) is different from the entry's hash, it knows it doesn't have to call equals at all. Just optimizing a bit.

提交回复
热议问题