0

If I have a java Hashtable or HashMap and load a bunch of entries with a set of keys, if I "clear()" it and then reload it with other entries using a subset of the same keys, will it reuse the same table-memory without thrashing? and not have to do a "rehash" or reallocation and rebuild of it's tables?

The reason is I have a pool of very dynamic records and want to reload them with different subsets of a common set of keyed elements efficiently - if it does not have to do any recalculations and rehashes after being cleared if I am using the same set of keys the table was originally built with that would be excellent. And I figured someone here might know rather than my spending a lot of time to go through the source code and test it :)

thanks!

peterk
  • 5,136
  • 6
  • 33
  • 47
  • You're being overly concerned with such details. I can guarantee you that you're spinning through 10 times as many objects doing whatever selection process you're doing. – Hot Licks Aug 26 '14 at 00:19
  • I find when dealing with very high speed manipulatation of large datasets these things are important. The proof is of course in testing. And the hashtable might be better used to look up indices into a fixed size array if that is practical. It depends on how sparse each record is relative to the total number of possible keys. – peterk Aug 27 '14 at 00:43
  • So, why haven't you simply examined the code to find out? – Hot Licks Aug 27 '14 at 01:47
  • someone may have already taken hours to test it :) – peterk Aug 28 '14 at 01:42

1 Answers1

1

The hash of each entry is recalculated no matter if the same objects existed on the Map before clearing it.

Indeed, the code of HashMap#put starts with:

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);   // hash the key everytime, no concept of cache

The main advantage of the clear method is to not set the HashMap to its initial capacity, avoiding any useless resizing. (https://stackoverflow.com/a/6757944/985949)

Community
  • 1
  • 1
Mik378
  • 21,881
  • 15
  • 82
  • 180
  • I assume it calls o.hashCode() and then calculates the integer. I wonder if it reuses the same table entries or allocataes new ones. My guess at this point is it preserves the base table (array) but that the entry itself and the linked list that contains the possibly multiple entries for each hash code are trashed and re-allocated. – peterk Aug 27 '14 at 00:41