Ads

Thursday, 2 November 2017

java.util.Hashtable in java


Hashtable class


This java class provides a means of organizing data based on some user-defined key structure.

It can store data as key & value.

It has two columns:

1.Key
2.Value

Constructors


Hashtable( )

The default constructor of the hash table it instantiates the Hashtable class.

Hashtable(int size)


This constructor accepts an integer parameter and creates a hash table that has an initial size specified by integer value size.

Hashtable(int size, float fillRatio)


This constructor 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.



Methods


Object put(Object key, Object value) 

This method is used to inserts a key and a value into the hash table. Returns null if the key isn't already in the hash table; returns the previous value associated with the key if the key is already in the hash table.

Object get(Object key)
 

This method returns the object that contains the value associated with the key. If the key is not in the hash table, a null object is returned.

Object remove(Object key) 

This method removes the key and its value. Returns the value associated with the key. If the key is not in the hash table, a null object is returned.

int size( ) 

This method returns the number of entries in the hash table.

boolean contains(Object value) 

This method returns true if some value equal to the value exists within the hash table. Returns false if the value isn't found.


Example


import java.util.*;
class Hashdemo
{
   public static void main(String args[])
   {
      Hashtable h1=new Hashtable();
      h1.put("A","Java");
      h1.put(2,"Xpert");
      System.out.println(h1.get("A"));
      Enumeration key=h1.keys();
      Enumeration value=h1.elements();       
      while(key.hasMoreElements());
      {
          System.out.println(key.nextElement());
          System.out.println(value.nextElement()); 
      }
   }
}        




Post a Comment

Click Here