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:


//a void (no arguments) constructor
Map map = new HashMap();
 
//a constructor with a single argument of type Map
Map newMap = new HashMap(map);

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:


// PUT operators
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(null, null);
map.put(5, null);

// GET operators
String value1 = map.get(1);
String value2 = map.get(2);

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:


Map m = Collections.synchronizedMap(new HashMap(...));

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:


for (Map.Entry entry : map.entrySet()) {
	map.remove(entry.getKey());
}

Exception:


Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextNode(Unknown Source)
	at java.util.HashMap$EntryIterator.next(Unknown Source)
	at java.util.HashMap$EntryIterator.next(Unknown Source)
	at com.javasampleapproach.HashMapTutorial.main(HashMapTutorial.java:35)

II. Practice

Full Example:


package com.javasampleapproach;

import java.util.HashMap;
import java.util.Map;

public class HashMapTutorial {
	public static void main(String[] args) {
		Map map = new HashMap();
		// PUT operators
		System.out.println("===PUT Operator===");
		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		map.put(4, "four");
		map.put(null, null);
		map.put(5, null);

		System.out.println("map size after put: " + map.size());
		// GET operators
		System.out.println("===GET Operator===");
		String value1 = map.get(1);
		String value2 = map.get(2);
		System.out.println(value1);
		System.out.println(value2);

		System.out.println("###Loop a Map with entrySet()");
		// LOOP a Map
		for (Map.Entry entry : map.entrySet()) {
			System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
		}

		// fail-fast case
		// because the Map is modified while iteration
		// Throw Exception

		System.out.println("Test FAIL-FAST!");
		for (Map.Entry entry : map.entrySet()) {
			map.remove(entry.getKey());
		}
	}
}

Result:


===PUT Operator===
map size after put: 6
===GET Operator===
one
two
###Loop a Map with entrySet()
Key : null Value : null
Key : 1 Value : one
Key : 2 Value : two
Key : 3 Value : three
Key : 4 Value : four
Key : 5 Value : null
Test FAIL-FAST!
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextNode(Unknown Source)
	at java.util.HashMap$EntryIterator.next(Unknown Source)
	at java.util.HashMap$EntryIterator.next(Unknown Source)
	at com.javasampleapproach.HashMapTutorial.main(HashMapTutorial.java:37)

III. Sourcecode

JavaHashMap

One thought on “How to work with Java HashMap”

Leave a Reply

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