How to work with Java HashMap

In the tutorial, JavaSampleApproach will introduce you how to work with Java HashMap

I. Concepts

Java HashMap is a construction of Map interface, so it provides all methods of Map interface.
Related post: How to work with Java Map Interface

– It permits a null key and null values
HashMap provides 3 Constructors:
– HashMap(): default initial capacity (16) and the default load factor (0.75).
– HashMap(int initialCapacity, float loadFactor)
– HashMap(Map m): constructs a new HashMap with the same mappings as the specified Map.
Note: In common case, we use empty constructor HashMap() & HashMap(Map m) constructors.

For insert and retrieve a key-value mapping, we uses: put() & get() methods.
– put(K key, V value)
– putAll(Map m)
– get(Object key)


Important! HashMap is not synchronized, so a best practice: should use it with single thread programming.
In case of multi-thread programming, we can use Collections.synchronizedMap to protect data for consistency but a performance problem will exist.

HashMap is fail-fast, it means if a map is structurally modified at any time after the iterator is created, a ConcurrentModificationException will be throwed.


II. Practice

Full Example:


III. Sourcecode


By grokonez | January 11, 2017.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

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