Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter. Eric S. Raymond

HashMap

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 20:52:15

0 Comments


Definition

Hashmap class uses hash table based implementation of the Map interface. It is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

Character

HashMap implement based on Hash table.
It permits null values and null key.
HashMap container is does not thread safe. Not synchronized with multiple threads.
Initial capacity and load factor affect the hashmap performance. When the number of entries exceed, it grows based on the load factor.
The fail-fast behavior of iterators should be used only to detect bugs.
Throw ConcurrentModificationException when the concurrent threads modify the objects.

source Code

								
package com.careerdrill.collections.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapUse {

	public static void main(String[] args) {
		Map< String,String > mMap = new HashMap< String,String >();
		mMap.put("C++", "Object oriented programming language");
		mMap.put("Java", "Platform independent language");
		mMap.put("SQL", "Enterprise database Software");
		mMap.put("C#", "Microsoft Programming language");

		Iterator< Entry < String, String > > iter = mMap.entrySet().iterator();

		while (iter.hasNext()) {
			Entry mEntry = iter.next();
			System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
		}

		mMap.put("C#", "Microsoft .NET language");

		System.out.println("Get value of 'C#': " + mMap.get("C#"));

	}

}
						

Output

    					 
C# : Microsoft Programming language
Java : Platform independent language
C++ : Object oriented programming language
SQL : Enterprise database Software
Get value of 'C#': Microsoft .NET language
    					 
					    

Comparison

Hashmap LinkedHashmap Treemap
Hashmap does not maintain any order. LinkedHashmap maintains insertion order. Treemap provides natural sorting.
LinkedHashmap and Hashmap allow null. LinkedHashmap and Hashmap allow null. Treemap does not allow null.
O(n) O(1) O(logn)
Implemented based on buckets. Maintaining insertion order using double buckets. Internally implement based on red block tree.
Compare using equals() and hashCode() methods. Compare using equals() and hashCode() methods. Comparable or comparator interface implementation.

When to use

When you want general purpose Set where you need to store only unique elements without any sorting or ordering requirement, you can use HashMap.

0 Comments



Please login to add comments.