Hashtable:-Hashtable
is a legacy class where object store in the form of key value pairs but key
cannot be null as well as values cannot be null. All the methods of Hashtable
class are synchronized.
Example1:-
TestHashtable.java
import java.util.*;
class TestHashtable
{
public static void main(String[]args)
{
Hashtable<Object,Object> m=new
Hashtable<Object,Object>();
m.put(101,"Sumit");
m.put(104,"Sunita");
m.put(102,"Suman");
m.put(107,"Sonu");
Set s=m.entrySet();
Iterator itr=s.iterator();
System.out.println("Key :::::::::Value");
while(itr.hasNext())
{
Map.Entry me=(Map.Entry)itr.next();
System.out.println(me.getKey()+" :::: "+me.getValue());
}
}
}
Output:-
Key
:::::::::Value
107 ::::
Sonu
104 ::::
Sunita
102 ::::
Suman
101 ::::
Sumit
Example2:-
TestHashtable.java
import java.util.*;
class TestHashtable
{
public static void main(String[]args)
{
Hashtable<Object,Object> m=new
Hashtable<Object,Object>();
m.put(101,"Sumit");
m.put(104,"Sunita");
m.put(102,"Suman");
m.put(107,"Sonu");
Set s=m.entrySet();
Iterator itr=s.iterator();
System.out.println("Key :::::::::Value");
while(itr.hasNext())
{
Map.Entry me=(Map.Entry)itr.next();
System.out.println(me.getKey()+" :::: "+me.getValue());
}
}
}
Output:-
Key :::::::::Value
107 ::::
Sonu
104 ::::
Sunita
102 ::::
Suman
101 ::::
Sumit
Example3:-
TestHashtable.java
import java.util.*;
class TestHashtable
{
public static void main(String[]args)
{
Map<Object,Object> m=new
Hashtable<Object,Object>();
m.put(101,"Sumit");
m.put(104,"Sunita");
m.put(102,"Suman");
m.put(107,null);
Set s=m.entrySet();
Iterator itr=s.iterator();
System.out.println("Key :::::::::Value");
while(itr.hasNext())
{
Map.Entry me=(Map.Entry)itr.next();
System.out.println(me.getKey()+" :::: "+me.getValue());
}
}
}
Output:-
Exception
in thread "main" java.lang.NullPointerException
Example4:-
TestHashtable.java
import java.util.*;
class TestHashtable
{
public static void main(String[]args)
{
Map<Object,Object> m=new
Hashtable<Object,Object>();
m.put(null,"Sumit");
Set s=m.entrySet();
Iterator itr=s.iterator();
System.out.println("Key :::::::::Value");
while(itr.hasNext())
{
Map.Entry me=(Map.Entry)itr.next();
System.out.println(me.getKey()+" :::: "+me.getValue());
}
}
}
Output:
- Exception
in thread "main" java.lang.NullPointerException
Comments
Post a Comment