Which is better option to use:
HashMap
with initial size: HashMap hm = new HashMap(10);
orHashMap
without initial size: HashMap hm = new HashMap()
? And why?
Also what is loadfactor
and modcount
in HashMap
's property?
When I debug my code in eclipse and look at value of HashMap
it shows a property named loadfactor
with a value of 0.75 and a property named modcount
with a value of 3.
Where i use hashmap in my code:-
I'm developing a communication application you can a say a chat application. in which i store all send/received messages in HashMap. Now as i cant assume how many messages will a user will send/receive i declare a hashmap without initial capacity. What i have written is
Map<String, Map<String, List<String>>> usersMessagesMap = new HashMap<String, Map<String,List<String>>>();
if i use it with initial capacity of 100 or higher will it effect the code?
Have you checked the HashMap API Javadoc?
On setting the initial size too high:
Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
Impact of the load factor on the performance:
As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.
Well, in short: depending on the estimated size and the expected growth ratio, you'll have to chose an aproximation or the opposite.
Usually, if you know the initial number of elements for your Map, it's recommended to set it at building time, avoiding early rehashes on initialization time.
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