Friday, June 17, 2016

Hashtable Class Java Example

Hashtable Class

Hashtable is similar to HashMap which can store elements in the form of key-value pairs.But Hashtable is synchronized .So in case of multi-threaded environment will get reliable result.

Default Initial Capacity= 11
Load Factor=0.75

Hashtable Class Methods


  • value put(key,value)
  • value get(Object key)
  • Set<K> keySet()
  • Collection<V> values
  • value remove(Object key)
  • void clear()
  • boolean isEmpty()
  • int size()
Program Sample:


/**

 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class HashtableDemo
{
/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException
{
Hashtable<String, Integer> ht=new Hashtable<>();
ht.put("Ajay", 50);
ht.put("Abhinaw", 100);
ht.put("Kapil", 88);
ht.put("Dhoni", 555);
ht.put("Tendulkar", 80);
System.out.println("The Player Names:");
Enumeration enuum=ht.keys();
while(enuum.hasMoreElements())
{
System.out.println(enuum.nextElement());
}
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Player Name:");
String name=br.readLine();
name=name.trim();
Integer score=ht.get(name);
if(score!=null)
{
int sc=score.intValue();
System.out.println(name + "Scored : " +sc);
}
else
System.out.println("Player not found");
}
}

OutPut:

The Player Names:
Ajay
Tendulkar
Dhoni
Abhinaw
Kapil

Enter Player Name:
Kapil
KapilScored : 88

No comments: