Hi Recently at an interview, I was asked that I have a Hashmap, an ArrayList and a Hashset. They each contain same 10 user defined objects (eg: Employee class object). Which will consume more heap space and why ?
I gave answer as Hashmap as it stores both key-value pair. But then Hashset also internally uses hashmap to store the values.
Thanks.
If you are counting both the memory required by the container and the memory required by the "10 user defined objects" then you are correct.
HashMap would occupy more space.
Even though HashSet is backed by a HashMap, the value it stores in all its entries is a reference to the same dummy instance.
Therefore a HashSet would require 10 key references + 10 value references + 10 elements + 1 dummy instance.
On the other hand a HashMap would require 10 key references + 10 value references + 10 key instances + 10 value instances (assuming the "10 user defined objects" are stored as values).
Of course, to be more accurate you have to also count the size of the array holding the HashMaps buckets, but that would be the same in both the HashMap and HashSet, since they contain the same number of elements.
Note that, as JB Nizet commented, if the key of the HashMap is a property of the "10 user defined objects", the "10 key instances" do not require additional memory (since they already exist), so both the HashMap and HashSet would require the same amount of memory for storing the 10 objects, with the HashSet actually requiring a bit more memory, since it holds a reference to a HashMap.
The ArrayList should take less memory than both the HashSet and HashMap, since the backing array of an ArrayList has a default initial length of 10 (which is enough to store the 10 objects), while the array of the buckets of a HashMap has a default initial length of 16 (also enough to store the 10 objects, assuming we use the default load factor of 0.75).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With