The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Initialize Map size

In my class I create about 10 different Maps. I thought of initializing the size. But I also thought is there going to be an advantage in doing so.

Approach1:
Map<String,String> myMap = new HashMap<String, String>(5);
Approch2:
Map<String,String> myMap = new HashMap<String, String>();
Per Approach2, the default capacity is 16. But will the memory allocation is more for approach2 compare to approach1?

Re: Initialize Map size

will the memory allocation is more for approach2

What Java programmer cares? If you're interested, you can try it both ways and inspect the heap and memory usage with a tool like jvisualvm. Unless you're writing code that's at the core of a high-throughput application, you're unlikely to feel the benefit of such a hand optimisation. Additionally, you may not see the same difference in memory allocation from one JVM to another, or possibly - thanks to the unpredictability of the garbage collector - even from one run of your code to another.