Hashtable rehash on remove

余生颓废 提交于 2019-12-11 05:27:51

问题


Does anyone know why the java jdk implementation of hashtable does not rehash the table upon remove ?

What if space usage is too low? Isnt it a reason to reduce size and rehash?

Just like load factor 0.75 which triggers rehash on put, we could have a lower bound like 0.25 (of course analysis can be done on the best value here) on the density of the table and trigger the rehash again, provided the size of the table is greater than the initialCapacity.


回答1:


Rehashing is an expensive operation and the java hash based data structures try to avoid it. They only do rehashing when the lookup performance is bad. This is the purpose of this type of data structure: lookup performance.

Here is a quote from the HashMap java docs:

The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

Beside this argument, the java creators might have thought that if you had that many elements in your hashtable the probability to have them again is quite large so there is no need to rehash twice the table.




回答2:


You should ask Sun/Oracle engineers in order to know why there is not a threshold to decrease size.

Here's my two cents:

  • Rehashing the table takes time
  • Checking on every remove operation takes time

On the other hand:

  • Probably you won't save much memory (objects and nodes within the table will use much more space)
  • There might not be many scenarios where first you create (some) very big hashtables and then empty them and crave for the unused space.
  • You know any popular implementation which includes that behaviour (decrease table size)

In programming as in life, there are lots of things that might be done. Some are only worth for very specific cases. Some are not worth the pain at all.



来源:https://stackoverflow.com/questions/12128288/hashtable-rehash-on-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!