Internal implementation of Hashtable in java
Hashtable is extends Dictionary abstract class and implements Map,
Cloneable,
and Serializable
interfaces, and it is legacy class which is introduced in java
1.0
public class Hashtable<K,V>
extends
Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
Hashtable is synchronized and
thread safe, that most of the methods of Hashtable are synchronized.
Few methods in Hashtable
public synchronized int size()
public synchronized V get(Object
paramObject)
public synchronized V put(K
paramK, V paramV)
public synchronized V
remove(Object paramObject)
public synchronized void putAll(Map<? extends K, ? extends V>
paramMap)
Hashtable allows only unique elements,
which mean it does not allow duplicate key’s but allows duplicate values.
HashTable does not allow the
null key’s and null values, if any case we pass the null key and
value into Hashtable then it will throw NullPointerException
Hashtable table=new Hashtable();
table.put(101, "emp1");
table.put(102, "emp2");
table.put(null, "emp3"); //java.lang.NullPointerException
Hashtable follows the hashing technique same like HashMap, while
storing the elements first of fall it will check hashcode of key and
then find the exact bucket to store the
elements.
Note : Initial capacity of Hashtable is 11
We have two options to iterate the
Hashtable elements by using Iterator
and Enumaration interfaces. Hashtable is fail-fast iterator, while
iterating elements by using Iterator
interface. If we perform any changes like add, remove elements then we
will get ConcurrentModificationException
In the same case Enumaration is not fail-fast
iterator.
Example for fail-fast iterator
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;
public class HashtableTest {
public static void main(String[] args) {
Hashtable<Integer,
String> table=new Hashtable<>();
table.put(101, "emp1");
table.put(102, "emp2");
table.put(103, "emp3");
Iterator
itr=table.entrySet().iterator();
while(itr.hasNext()){
Entry
entry=(Entry) itr.next();
System.out.println(entry.getKey()+"...."+entry.getValue());
table.put(104, "emp4"); //adding element
}
}
}
Insertion order not preserved and
it is based on hashcode of key’s
Hashtable is the best choice for if
our frequent operation is search operation.
No comments:
Post a Comment