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

后端 未结 4 413
梦毁少年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:59

    You are right, but considering that increasing the array is a much more expensive operation, it's not unreasonable for the HashMap to think "once the user has increased the array, chances are he'll need the array this size again later" and just leave the array instead of decreasing it and risking to have to expensively expand it later again. It's a heuristic I guess - you could advocate the other way around too.

提交回复
热议问题