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.
Example:

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

Example:

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.
Sample:

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.
Example:

Exception:

II. Practice

Full Example:

Result:

III. Sourcecode

JavaHashMap


Related Posts



Got Something To Say:

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

*