Submitted by: Octavia Anghel(octaviaanghel@gmail.com)

Wednesday Jan 17th 2018 by Octavia Anghel

Language: Java, Level: Beginner: - See how to avoid having the HashMap resize half way through the insertion.

Map map = new HashMap(collection.size());
for (Object obj : collection) {
       map.put(obj.key, obj.value);

The code above wants to make sure that the HashMap doesn't need to be resized, so its sets the initial size to the number of elements that it will use. But, the HashMap implementation doesn't behave like this, it sets its internal threshold to threshold = (int)(capacity * loadFactor), this means that it will resize after 75% of the collection has been inserted into the map, causing extra garbage. Avoid this using the code below:

Map map = new HashMap(1+ (int) (collection.size() / 0.75));
Mobile Site | Full Site