Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many elements can I store in a HashMap object in Java [duplicate]

Tags:

java

hashmap

I know that is determined by the memory available in the system, and also depending on a good hash function, but in general I'd like to know what is the biggest map you have used, and if it worked well out of the box or needed any adjustment to make it work adequately.

like image 640
Leo Avatar asked Nov 10 '13 03:11

Leo


People also ask

What happens in HashMap If enter duplicates?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

How count duplicate values in HashMap?

You can simply write multiMap. put("DM", "123"); . And mind, that you should switch your key and value. DM should be the key.

What is the maximum number of entries you can store in HashMap?

Is there a theoretical limit for the number of key entries that can be stored in a HashMap or does it purely depend on the heapmemory available ? Looking at the documentation of that class, I would say that the theoretical limit is Integer. MAX_VALUE (231-1 = 2147483647) elements.


1 Answers

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

like image 146
torquestomp Avatar answered Sep 28 '22 06:09

torquestomp