Why is resize implemented the way it is?

后端 未结 1 1096
生来不讨喜
生来不讨喜 2020-12-15 17:38

I have several questions about rebuilding HashMaps when adding new key-values pair. I will ask questions based on these facts (they are true for Oracle JVM, not

相关标签:
1条回答
  • 2020-12-15 18:28

    Yes, these facts are correct.

    1. Detecting whether it is "obviously not necessary" would take a lot of time, and it's almost always redundant, since the case where all the keys have the same hash code is rare. In short, you're paying a significant expense (tracking how common one particular hash code is) for everybody just to save some work in an extremely rare case, which will end up costing more than it saves.
    2. Because removing is a somewhat less common operation, and it's usually followed by refilling the map. If you want to start the map over with a smaller table, you can just assign it to a new HashMap and let the old one be garbage-collected.
    0 讨论(0)
提交回复
热议问题