In C++ itís harder to shoot yourself in the foot, but when you do, you blow off your whole leg. Bjarne Stroustrup

Hashtable

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

0 Comments


Definition

Hashtable is a class which stores the keys and values. All the methods in the hash table are synchronized and thread safe. Hashtable implemented Dictionary which is obsolete now and Oracle recommends to implement the Map interface.

Character

Objects used as keys must implement the hashCode method and the equals method.
The iterator will throw a ConcurrentModificationException.
The fail-fast behavior of iterators should be used only to detect bugs.
Oracle recommends making use Hashmap compare than a hash table. If the application requires thread support, use concurrent hash map.
Initial capacity controls a tradeoff between wasted space and the need for rehash operations.

source Code

								
package com.careerdrill.collections.map;

import java.util.Hashtable;
import java.util.Set;

public class HashtableUse {

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

		 Set< String > keys = htab.keySet();
	        for(String key: keys){
	            System.out.println("Value of "+key+" is: "+htab.get(key));
	        }
	
	}

}
						

Output

    					 
Value of Java is: Platform independent language
Value of C++ is: Object oriented programming language
Value of SQL is: Enterprise database Software
Value of C# is: Microsoft Programming language
    					 
					    

Comparison

Hash table Hash map
Synchronized and thread safe. Non-synchronized and not thread safe.
do not allow null keys and null values. Hashmap allows one null key and any number of null values.
Not fail-fast iterator. Uses fail-fast iterator.
Hashtable slower than hash map due to thread synchronization support. Faster compare than Hashtable.
Hashtable derived from Dictionary which is obsolete now. Hash map extended from AbstractMap class.

When to use

When you want thread safe hash, you can use Hash table. The hash table allows only one thread at a time. If you are looking for concurrent access, you can use ConcurrentHashMap.

0 Comments



Please login to add comments.