Seetharaman Venkatasamy wrote:
and in HashMap when ever rehashing happen the size will be doubled. if there are very few element after the rehashing then huge space will be wasted. is there any way to trim it or am i missing something here.
should i go for TreeMap where there is a space constraint?
Greg Charles wrote:It's a rare situation where you need to retain the HashMap after removing a significant number of elements in it.
Mike Simmons wrote:If you're using a java.util.HashMap, check out the source code. I believe you will find that the size of the bucket table will always be a power of two.
Jeff Verdegan wrote:
Mike Simmons wrote:If you're using a java.util.HashMap, check out the source code. I believe you will find that the size of the bucket table will always be a power of two.
Oh, right, I forgot about that.
So that negates the suggestion of pre-sizing or copying to a new map after filling.
Greg Charles wrote:
No. At least the version I'm looking at shows:
That is, it's not always a power of two.
Seetharaman Venkatasamy wrote:
length multiply by 2
Jeff Verdegan wrote: the constructor I snipped above ensures that it always starts out as a power of 2.
Seetharaman Venkatasamy wrote:
Jeff Verdegan wrote: the constructor I snipped above ensures that it always starts out as a power of 2.
bit confused I am. only *initial capacity* is marked as power of 2. and then when ever rehashing occur then *growing rate* is multiply by 2 only. (obviously the number is power of 2 but not growing rate)
Jeff Verdegan wrote:
We start with an initial capacity that's always a power of 2. Then, when we resize, we always multiply by 2. Thus, the number of buckets of a HashMap will always be a power of 2.
Greg Charles wrote:Interesting. I was looking at the first Google hit for HashMap source, which seems to be out of date. I would have thought hash tables would have been well enough understood to get HashMap right in the first implementation, but apparently not!
Greg Charles wrote:It's a rare situation where you need to retain the HashMap after removing a significant number of elements in it. If that's what you really need to do though, you could iterate through it and add the elements to a pristine, unbloated HashMap.
Martin Vajsar wrote:
Greg Charles wrote:It's a rare situation where you need to retain the HashMap after removing a significant number of elements in it. If that's what you really need to do though, you could iterate through it and add the elements to a pristine, unbloated HashMap.
Actually, new MashMap<...>(bloatedMap) would work as good. The copy constructor does not inherit the old capacity from the map;
Consider Paul's rocket mass heater. |