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

前端 未结 3 1927
灰色年华
灰色年华 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条回答
  •  南方客
    南方客 (楼主)
    2021-01-18 03:04

    It's just an optimization: comparing two integers is faster than calling equals().

    If the two hashcodes differ, then, based on the contract of equals and hashCode, the map knows that the existing key isn't equal to the given key, and can go faster to the next one.

提交回复
热议问题