• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating a HashMap with initial capacity  RSS feed

 
Elinor Chang
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If creating a HashMap with known capacity beforehand and the size of the HashMap will NOT change, is the HashMap object should be initilized with a capcacity as the following:

HashMap hm = new HashMap(100);

instead of

HashMap hm = new HashMap();

Is there performance impact if specifying the initial capcaity or not?

Thanks!
 
Chetan Parekh
Ranch Hand
Posts: 3640
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you create with initiate capacity, it will definitely have optimum performance then creating without initial capacity.
 
Mark Wuest
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Elinor Chang:
If creating a HashMap with known capacity beforehand and the size of the HashMap will NOT change, is the HashMap object should be initilized with a capcacity as the following:

HashMap hm = new HashMap(100);

instead of

HashMap hm = new HashMap();

Is there performance impact if specifying the initial capcaity or not?


Since I *just* did this, it's fresh in my usually forgetful mind: yes, and it's actually explained reasonably well (along with load factor) in the API docs for HashMap.

I'll forget all of this in a couple of days, and the next time I use a HashMap I'll end up looking at the docs again.

Mark
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!