A HashMap
in Java can have a maximum of 2^30 buckets for storing entries - this is because the bucket-assignment technique used by java.util.HashMap
requires the number of buckets to be a power of 2, and since ints are signed in Java, the maximum positive value is 2^31 - 1, so the maximum power of 2 is 2^30.
However, there is in fact no programmatic limit on how many key/value pairs you can store in a HashMap - the size()
function will just stop being accurate once you pass 2^31 - 1. This is because of the way collisions are handled - key/value pairs that land in the same bucket are linked, like nodes in a LinkedList
.
In general, though, if you're getting anywhere close to 2^30 things you need to keep track of in a real-world application, you need a lot more RAM than you can rely on in one machine. The largest HashMap I've ever worked with that sat in a single JVM had a few tens of millions of entries, all very lightweight