Spread the love

Class Hashtable in Java

Spread the love

All About Class Hashtable in Java

The Hashtable class is a concrete subclass of Dictionary that builds a table of key/value pairs.
Any non-null object can be used as a key or as a value. The objects used as keys must implement the equals() and hashCode() methods in a way that computes comparisons and hashcodes from the contents of an object. Once the table is built, a value can be efficiently retrieved by supplying its associated key.

Hashtable is a subclass of Dictionary class that maps unique keys to values. Values can be duplicated. Hashtable also implements interfaces like Cloneable and Serializable. The Hashtable is used to store values in the form of Map key with a value.

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 affect its efficiency. They are:

  • Capacity
  • Load factor(range between 0.0 to 1.0)

The importance of Load factor:

Hashtable is an excellent example of how a well-written class can hide an arcane algorithm. The casual user simply instantiates a Hashtable and uses put() and get() to add and retrieve key and value pairs. However, when performance is an issue, we need to be aware of the considerations.

Internally, a Hashtable keeps an array of key/value pairs. When a new key/value pair is added to a Hashtable, it is added to the array at an index that is calculated from the hashcode of the key. If a key/value pair already exists at this index, the new pair is linked to the existing key and value. Thus, a Hashtable has an overall structure of an array of linked lists.

For a given key, the retrieval of the matching value from a Hashtable is quite fast. The Hashtable computes the hashcode of the key and uses it as an index into the array. Then it only needs to search the linked list of key/value pairs at that index to find a match for the given key. If the array is short, but the Hashtable contains many key/value pairs, however, the linked lists will be lengthy, which adversely affects performance.

A Hashtable has a capacity, which is the length of its array, and a load factor, which determines when rehashing is performed. A load factor is a number between 0 and 1. If the number of key/value pairs added to the Hashtable exceeds the capacity multiplied by the load factor, the capacity of the Hashtable is increased and the key/value pairs are rehashed into the new array. Obviously, this is an undesirable performance hit, so if you know approximately how many items you will add to a Hashtable, you should create one with an appropriate initial capacity.

READ  Class OutputStream in Java
READ  Bean Customizer in Java

The key needs to be a nonnull object and corresponding value also needs to be nonnull. To

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, the 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.

Hashtable class implements a hashtable data structure, which allows us to associate values with a key and to efficiently look up the value associated with a given key. A hashtable is essentially an associative array, which stores object with non-numeric array indices.

put() associates a value with a key in a Hashtable. get() retrieves a value for a specified key. remove() deletes a key/value association. keys() and elements() return Enumeration objects that allow you to iterate through the complete set of keys and values stored in the table.

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,java.io.Serializable{
//constructors:
public Hashtable();//constructs a new empty Hashtable with default initial capacity-11
//and loadfactor as 0.75
public Hashtable(int initialCapacity);//constructs a new empty Hashtable with 
//the initial capacity specified in the argument.The load factor is default as 0.75.
public Hashtable(int initialCapacity,float loadFactor);//constructs a new empty Hashtable with 
//the initial capacity and loadFactor specified in the arguments.
public Hashtable(Map m);//creates a new Hashtable from the Map specified.
//Methods:
public synchronized void clear();
protected void rehash();
public synchronized Object clone();
public synchronized boolean contains(Object value);
public boolean isEmptry();
public synchronized boolean containsKey(Object key);
public synchronized Object get(Object key);
public synchronized Object put(Object key,Object value);
public synchronized Object remove(object key);
public int size();
public synchronized Enumeration elements();
public synchronized Enumeration keys();
public synchronized String toString();
}

The details of the class structure are given as follows:

public Hashtable();

public Hashtable() constructor creates a Hashtable with a default capacity of 101 and a default load factor of .75.

public Hashtable(int initialCapacity);

public Hashtable(int initialCapacity) method constructor creates a Hashtable with the given capacity and a default load factor of .75.

READ  Class SecurityManager in Java

Parameter
initialCapacity – The initial capacity.

public Hashtable(int initialCapacity, float loadFactor);

public Hashtable(int initialCapacity, float loadFactor) constructor creates a Hashtable with the given capacity and load factor.

Parameter
initialCapacity – The initial capacity.
loadFactor – The load factor.

public synchronized void clear();

public synchronized void clear() method removes all of the key/value pairs from this Hashtable.

public synchronized Object clone();

public synchronized Object clone() method returns a shallow copy of this Hashtable. This means that the internal array of the Hashtable is copied, but the keys and values themselves are not copied.

READ  Class ParserException in Java

This method returns a copy of this Hashtable.

public synchronized boolean contains(Object value);

public synchronized boolean contains(Object value) method returns true if the given value is contained in this Hashtable object. The entire table is searched, which can be a time-consuming operation.

This method returns true if this Hashtable contains the given value; false otherwise.

Parameter
value – The value to find.

public synchronized boolean containsKey(Object key);

public synchronized boolean containsKey(Object key) method returns true if the given key is contained in this Hashtable object. Because the key is hashed to perform the search, this method runs quite fast, especially in comparison to contains().

This method returns true if this Hashtable contains the given value; false otherwise.

Parameter
key – The key to find.

public synchronized Enumeration elements();

public synchronized Enumeration elements() method returns an Enumeration that iterates through the values in this Hashtable.

This method returns the values in this Hashtable as an Enumeration.

public synchronized Object get(Object key);

public synchronized Object get(Object key) method returns the value that is associated with the given key.

This method returns the value that corresponds to this key or null if the key is not associated with any value.

Parameter
key – The key of the value to retrieve.

public boolean isEmpty();

public boolean isEmpty() method returns a boolean value that indicates whether or not the Hashtable is empty.

READ  Class DatagramPacket in Java

This method returns true if there are no values in the Hashtable; false otherwise.

public synchronized Enumeration keys();

public synchronized Enumeration keys() method returns an Enumeration that iterates through the keys in this Hashtable.

This method returns the keys in the Hashtable as an Enumeration.

public synchronized Object put(Object key, Object value);

public synchronized Object put(Object key, Object value) method associates the given key with the given value in this Hashtable.

This method returns the previous value associated with the given key or null if the key has not previously been
associated with a value.

Parameter
key – A key object.
value – A value object.

public synchronized Object remove(Object key);

public synchronized Object remove(Object key) method removes a key/value pair from this Hashtable. If the given key is not in the Hashtable, the method does nothing.

This method returns the value associated with the given key, or null if the key is not associated with a value.

Parameter
key – A key of the value to remove.

public int size();

public int size() method returns the number of key/value pairs in the Hashtable.

This method returns the number of keys in the Hashtable.

public synchronized String toString();

public synchronized String toString() method returns a string representation of this Hashtable. The string includes every key/value pair that is contained in the Hashtable, so the string returned by toString() can be quite long.

This method returns a string that represents this Hashtable.

protected void rehash();

protected void rehash() method increases the capacity of this Hashtable. A larger internal array is created and all
existing key/value pairs are rehashed into the new array.

READ  Class FileDescriptor in Java

Apart from these Hashtable class also has inherited methods from class- Object. They are as follows:

  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • wait(long)

public Hashtable(int initialCapacity) throws IllegalArgumentException if the initial capacity is less than or equal to zero.

An example:


import java.util.*;
public class HashtableTest{
     public static void main(String []args){
        Hashtable ht=new Hashtable();
        ht.put("Item-1","Apple");
        ht.put("Item-2","Orange");
        ht.put("Item-3","Banana");
        Enumeration e=ht.keys();
        while(e.hasMoreElements())
        {
            String st=(String)e.nextElement();
            System.out.println(ht.get(st));
        }
     }
}
 

The output of the code:
$javac HashtableTest.java
Note: HashtableTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint: unchecked for details.
$java -Xmx128M -Xms16M HashtableTest
Banana
Orange
Apple




Spread the love
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special keyword called...

Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Super Keyword in Java Simplified

Super Keyword Super Keyword in Java Simplified: Java defines a special...

Learn Object Repository in UFT in An Efficient and Fast Manner

Object Repository in UFT The post will cover the following...

Learn What Primary Tools For Test Automation

Primary Tools For Test Automation According to the Gartner report...

EDITOR PICKS


Spread the love