Is Java HashMap.clear() and remove() memory effective?

后端 未结 4 405
梦毁少年i
梦毁少年i 2020-12-02 12:40

Consider the follwing HashMap.clear() code:

 /**
 * Removes all of the mappings from this map.
 * The map will be empty after this call returns.         


        
4条回答
  •  一生所求
    2020-12-02 12:40

    Looking at the source code, it does look like HashMap never shrinks. The resize method is called to double the size whenever required, but doesn't have anything ala ArrayList.trimToSize().

    If you're using a HashMap in such a way that it grows and shrinks dramatically often, you may want to just create a new HashMap instead of calling clear().

提交回复
热议问题