Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better option for HashMap?

Tags:

java

hashmap

Which is better option to use:

  • HashMap with initial size: HashMap hm = new HashMap(10); or
  • HashMap 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?

like image 809
Harry Joy Avatar asked Dec 07 '22 23:12

Harry Joy


1 Answers

Have you checked the HashMap API Javadoc?

  • The capacity is the number of buckets in the hash table
  • The initial capacity is simply the capacity at the time the hash table is created
  • The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased

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.

like image 122
Tomas Narros Avatar answered Dec 10 '22 13:12

Tomas Narros