Friday, 1 May 2015

Java Hashtable class

Java Hashtable class
  • A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class.
  • It contains only unique elements.
  • It may have not have any null key or value.
  • It is synchronized.
Example of Hashtable:
1.    import java.util.*;  
2.    class TestCollection16{  
3.     public static void main(String args[]){  
4.       
5.      Hashtable<Integer,String> hm=new Hashtable<Integer,String>();  
6.      
7.      hm.put(100,"Amit");  
8.      hm.put(102,"Ravi");  
9.      hm.put(101,"Vijay");  
10.   hm.put(103,"Rahul");  
11.   
12.   for(Map.Entry m:hm.entrySet()){  
13.    System.out.println(m.getKey()+" "+m.getValue());  
14.   }  
15.  }  

16. }  

Output:103 Rahul
       102 Ravi
       101 Vijay
       100 Amit



Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMap
Hashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.
Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.
Hashtable is a legacy class.
4) HashMap is fast.
Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.
Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.
Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.
Hashtable inherits Dictionaryclass.

No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...