Just a few minutes back I answered a question asking about the "Maximum possible size of HashMap in Java". As I have always read, HashMap is a growable data-structure. It's size is only limited by the JVM memory size. Hence I thought that there is no hard limit to its size and answered accordingly. (The same is applicable to HashSet as well.)
But someone corrected me saying that since the size() method of HashMap returns an int, there is a limit on its size. A perfectly correct point. I just tried to test it on my local but failed, I need more than 8GB memory to insert more than 2,147,483,647 integers in the HashMap, which I don't have.
My questions were:
- What happens when we try to insert 2,147,483,647 + 1 element in the HashMap/HashSet?
- Is there an error thrown?
- If yes, which error? If not what happens to the HashMap/HashSet, its already existing elements and the new element?
If someone is blessed with access to a machine with say 16GB memory, you can try it out practically. :)