Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Theoretical limit for number of keys (objects) that can be stored in a HashMap?

Is there a theoretical limit for the number of key entries that can be stored in a HashMap or does the maximum purely depend on the heap memory available?

Also, which data structure is the best to store a very large number of objects (say several hundred thousand objects)?

like image 400
Ebbu Abraham Avatar asked Nov 08 '10 12:11

Ebbu Abraham


People also ask

What is the limit of HashMap in Java?

The hashing function is applied to the key object to calculate the index of the bucket in order to store and retrieve any key-value pair. Capacity is the number of buckets in the HashMap. The initial capacity is the capacity at the time the Map is created. Finally, the default initial capacity of the HashMap is 16.

Why initial capacity of HashMap is 16?

Initial Capacity of HashMap The initial capacity of the HashMap is the number of buckets in the hash table. It creates when we create the object of HashMap class. The initial capacity of the HashMap is 24, i.e., 16. The capacity of the HashMap is doubled each time it reaches the threshold.

Can we store 3 values in HashMap?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key.

Can we store objects as key in HashMap?

Answer to your question is yes, objects of custom classes can be used as a key in a HashMap.


1 Answers

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.

This is because to properly implement this class, the size() method is obliged to return an int representing the number of key/value pairs.

From the documentation of HashMap.size()

Returns: the number of key-value mappings in this map

Note: This question is very similar to How many data a list can hold at the maximum.


which data structure is the best to store a very large number of objects(say several hundred thousand objects)?

I would say it depends on what you need to store and what type of access you require. All built in collections are probably well optimized for large quantities.

like image 187
aioobe Avatar answered Oct 14 '22 17:10

aioobe