4 ms·
What's weird about the original article is that my understanding of HashMap (which as you pointed out, is the backing data structure of for HashSet) does not in
by stygiansonic 7y ago
What's weird about the original article is that my understanding of HashMap (which as you pointed out, is the backing data structure of for HashSet) does not initialize the underlying hash table until first use - so if a bunch of new HashSets were created but never added to, the memory impact should be minimal irregardless of what the initial capacity was set to. (So there should not have been much of a difference between "new HashSet()" and "new HashSet(0)" if no items were ever added)
See this comment, and also the implementation of putVal()/resize():
https://hg.openjdk.java.net/jdk/jdk14/file/f77e9e27b68d/src/java.base/share/classes/java/util/HashMap.java#l387 https://hg.openjdk.java.net/jdk/jdk14/file/f77e9e27b68d/src/...
Perhaps things were different back in Java 1.3.
EDIT: Apologies, I completely missed this in the article, where it's explicitly called out.
This particular trick also no longer works. As I found out while writing this article, modern JDKs do not allocate any space in a HashSet until something is added. If I had kept applying this trick pre-emptively I would have been wasting my time.