All About Class Hashtable in Java

Hashtable is a subclass of Dictionary class which maps keys to values. Any key needs to be non null object and corresponding value also needs to be non null.To successfully store and retrieve objects from a  Hashtable,the objects used as keys must implement the hashCode() and equals() methods.An instance of Hashtable has two parameters that affects its efficiency. They are:

  • Capacity
  • Load factor(range between 0.0 to 1.0)
When the entries in the Hashtable exceeds the product of load factor and the current capacity, the capacity is increased by calling rehash() method.More the larger the load factor, more the Hashtable will use memory efficiently,at the expense of larger expected time per lookup.If many entries are to be performed into Hashtable,we need to create a large capacity Hashtable that will allow entries to inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.As it extends the Dictionary class,hence it will get all the methods defined in the Dictionary class.
an example of Hashtable:

//create a Hashtable
Hashtable numbers=new Hashtable();
//insert objects into Hashtable
numbers.put("one",new Integer(1));
numbers.put("two",new Integer(2));
numbers.put("three",new Integer(3));
retrive a number from Hashtable
Integer n=(Interger)numbers.get("two");
if(n!=null)
System.out.println("two"+n);
 
The class Hashtable is defined as:

public class java.util.Hashtable extends java.util.Dictionary implements java.lang.cloneable{
//constructors:
public Hashtable();//constructs a new empty Hashtable.
public Hashtable(int initialCapacity);//constructs a new empty Hashtable with the initial capacity specified in the argument.
//Methods:
public void clear();
protected void rehash();
public Object clone();
public boolean contains(Object value);
public boolean isEmptry();
public boolean containsKey(Object key);
public Object get(Object key);
public Object put(Object key,Object value);
public Object remove(object key);
public int size();
public Enumeration elements();
public Enumeration keys();
public String toString();

}
 
public Hashtable(int initialCapacity) throws IllegalArgumentException if the initail capacity is less than or equal to zero
All About Class Hashtable in Java All About Class Hashtable in Java Reviewed by Animesh Chatterjee on September 26, 2018 Rating: 5

No comments:

Powered by Blogger.