Showing posts with label HashTable. Show all posts
Showing posts with label HashTable. Show all posts

Saturday, 28 May 2011

HashTable in java

Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, Java 2 reengineered Hashtable so that it also implements the Map interface. Thus, Hashtable is now integrated into the collections framework. It is similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode() and equals() methods that are defined by Object. The hashCode() method must compute and return the hash code for the object. Of course, equals() compares two objects. Fortunately, many of Java's built-in classes already implement the hashCode() method. For example, the most common type of Hashtable uses a String object as the key. String implements both hashCode() and equals().

Constructors of HashTable class

Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map m)

 

The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The third version creates a hash table that has an initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.

 

Examples on HashTable


Saturday, 14 May 2011

Performance of Map interface implementations

Hashtable

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

HashMap

This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.
Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

 

TreeMap

The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.

 

LinkedHashMap

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

Sunday, 17 April 2011

Getting keys from hashtable: Iterating over hashtable

Consider the hashtable:

Hashtable ht = new Hashtable(); 
ht.put("1","One");
ht.put("2","Two");
ht.put("3","Three");

Now getting the keys set can be got as follows:

As a set
Set st = ht.keySet();

System.out.println("Set created from Hashtable Keys contains :");
//iterate through the Set of keys
Iterator itr = st.iterator();
while(itr.hasNext())
System.out.println(itr.next());
Note:
Please note that resultant Set object is backed by the Hashtable.
Any key that is removed from Set will also be removed from
original Hashtable object. The same is not the case with the element addition.
Eg.
st.remove("2");

Getting from enum:
Enumeration e = ht.keys();
while(e.hasMoreElements())
System.out.println(e.nextElement());
}


Thursday, 31 March 2011

HashMap vs HashTable

At the outset, both are similar in functionality (purpose) but for very small difference. Both store data in key/value pairs. There is nothing with HashMap that cannot be done with Hashtable.
Following table gives the differences.
Hashtable HashMap
Introduced with JDK 1.0 version, the starting version of Java Introduced with JDK 1.2
Part of legacy classes (the data structures of JDK 1.0 are known as legacy classes) Part of Collections framework
Methods of Hashtable are synchronized by default Methods are not synchronized by default
Does not permit null values (trying to add, throws NullPointerException) Permits null values (either key or value)
Enumeration interface is used for iterating keys Iterator is used for iterating the keys
Enumerator is not fail-fast Iterator is fail-fast
Safe for multithreaded applications Better for non-threaded applications
Low performance due to synchronization High performance
Hashtable is serialized HashMap is not serialized
Hashtable can make use of HashMap methods to get the features of collections framework. As of JDK 1.2, the Hashtable implements Map. Following is the class signature of Hashtable.
public class java.util.Hashtable extends java.util.Dictionary implements java.util.Map, java.lang.Cloneable, java.io.Serializable
What is synchronized?
The concept of synchronization comes in multithreading. In multithreaded applications, there is every chance that multiple threads accessing the same source of data at the same time. This results in data corruption and data inconsistency. Synchronization avoids this by allowing only one thread to access the resource of data at a time.
That is, when one thread is modifying the data of Hashtable, the other thread cannot modify. The other thread should wait until the first one completes its job. This is done by acquiring the lock on Hashtable by the first thread. The lock will not be released until the first completes its job.
What is fail-fast?
The concept of fail-fast comes with iterators. When an Iterator object is created and iteration is going on, the HashMap elements cannot be modified (like addition or deletion of elements cannot be done). This is explained programmatically in ConcurrentModificationException.
Even though the HashMap methods are not synchronized, we can obtain a synchronized HashMap optionally as follows.
Map m = Collections.synchronizeMap(HashMap);
Programs on Hashtable and HashMap are available at Hashtable Examples and HashMap Examples.
About Hashing and Hashcode
Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.
Hashing is process of converting a string or object into a 32-bit integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination of equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.

Saturday, 12 March 2011

Comparison of map and hashtable

If you've used Hashtable, you're already familiar with the general flavor of Map. (Of course Map is an interface, while Hashtable is a concrete implementation.) Here are the major differences:
  • Map provides Collection-views in lieu of direct support for iteration via Enumeration objects. Collection-views greatly enhance the expressiveness of the interface, as discussed later in this lesson.
  • Map allows you to iterate over keys, values, or key-value pairs; Hashtable did not provide the third option.
  • Map provides a safe way to remove entries in the midst of iteration; Hashtable did not.
Further, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, as the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the consistency of the interface: containsValue parallels containsKey nicely.

Monday, 29 November 2010

Iterate through values of Java Hashtable example

This example shows how to iterate over hash table using enumerator:

//create Hashtable object    
Hashtable ht = new Hashtable();
//add key value pairs to Hashtable
ht.put("1","One");
ht.put("2","Two");
ht.put("3","Three");
//get Enumeration of values contained in Hashtable using
//Enumeration elements() method of Hashtable class
Enumeration e = ht.elements();
//iterate through Hashtable values Enumeration
while(e.hasMoreElements())
System.out.println(e.nextElement());

Monday, 20 September 2010

Hashtable example in java

Here we will take example of hash table class in java. To jump to full example jump here.

Creating the hash table:

//Creating hashtable with default initial capacity
HashTable hashtable= new HashTable();
//To specify initial capacity,use following constructor.
Hashtable hashtable = new Hashtable(100);
//To create hashtable from map use following constructor
Hashtable hashtable = new Hashtable(Map myMap);


Putting the values


For this put method is used. Eg.


hastable.put("One",new Integer(1));


To copy all key - value pairs from Map to Hashtable use putAll method.Signature of putAll method is, void putAll(Map m).


Getting the values


Use get method of Hashtable to get value mapped to particular key.Signature of the get method is,

Object get(Object key)


Removing the elements



To remove elements from hashtable use remove method.Signature of remove methid is, 


Object remove(Object key)

This method returns value that had mapped to the given key, otherwise null if mapping not found.         


//To remove particular key - value pair 
//from the Hashtable use remove method.
hashtable.remove("One");

 

To check if hashtable is empty or not

To check whether Hashtable is empty or not, use isEmpty() method.isEmpty() returns true is Hashtable is empty, otherwise false.


To check if element exists:


Finding particular value from the Hashtable : Hashtable's contains method returns boolean depending upon the presense of the value in given hashtable.Signature of the contains method is,


boolean contains(Object value) 


To check if key exists


Finding particular Key from the Hashtable : Hashtable's containsKey method returns boolean depending upon the presense of the key in given hashtable.Signature of the method is, boolean containsKey(Object key)


Iterating over hash table



Iterating over keys

To get all keys stored in Hashtable use keys method.Signature of the keys method is,Enumeration keys()To get Set of the keys use keySet() method instead.Set keySet()


Iterating over values


To get all values stored in Hashtable use elements method. Signature of the elements method is, Enumeration elements() To get Set of the values use entrySet() method instead.


Full Code Example of Hashtable



import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableExample{
public static void main(String args[]){
// constructs a new empty hashtable
//with default initial capacity
Hashtable hashtable = new Hashtable();


//Puting the values in hashTable
hashtable.put( "One", new Integer(1) ); // adding value into hashtable
hashtable.put( "Two", new Integer(2) );
hashtable.put( "Three", new Integer(3) );
/*
We CAN NOT add primitives to the hashtable.

*We have to wrap it into one of the wrapper before adding.
*/
//get number of keys present in the hashtable
System.out.println("Hashtable contains " + hashtable.size() + " key value pair.");

if( hashtable.contains( new Integer(1) ) ){
System.out.println("Hashtable contains 1 as value");
}else{
System.out.println("Hashtable does not contain 1 as value");
}
if( hashtable.containsKey("One") ){
System.out.println("Hashtable contains One as key");
}else{
System.out.println("Hashtable does not contain One as value");
}
Integer one = (Integer) hashtable.get("One");
System.out.println("Value mapped with key \"One\" is " + one);
/*
IMPORTANT: get method returns Object, so we need to downcast it.
*/

System.out.println("Retriving all keys from the Hashtable");
Enumeration e = hashtable.keys();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//iterating over values
System.out.println("Retriving all values from the Hashtable");
e = hashtable.elements();
while( e. hasMoreElements() ){
System.out.println( e.nextElement() );
}
//removing the element
System.out.println( hashtable.remove("One") + " is removed from the Hashtable.");
}
}