Java 19 – New method to create pre-allocated HashMaps()

What are the new methods?

This hasn’t really been mentioned into JDK enhancements proposal for Java 19. But can be found in the release notes.

Map<String, Integer> map = HashMap.newHashMap(100);

Why is this?

Hashmaps has a default loading factor of 0.75, which when the HashMaps reaches 75% capacity, it rebuilds with double the size. With using the new method the loading factor is automatically taken into account.

Final Thoughts

Quite a handy method if you are creating pre-allocated HashMaps. This has also been added to LinkedHashedMaps & WeakHashMaps

Leave a Reply

Your email address will not be published. Required fields are marked *