Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the difference between Hashtable and HashMap classes?

 
Alexey Korneychuk
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, ranches!

Why does run-time exception occur?
What is the difference between Hashtable and HashMap classes?

public class J {

public static void main(String[] args) throws Exception {
HashMap hm = new HashMap();
hm.put(null, null);
System.out.println(hm);

Thread.sleep(1000);

Hashtable ht = new Hashtable();
ht.put(null, null);
System.out.println(ht);


}
}

Result:
{null=null}
java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:397)
at fgff.Jhsdhdjshdjhsdjhjhjsdhjs.main(J.java:28)
Exception in thread "main"

Alexey
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are the main differences between HashMap & Hashtable:

Hashtable does not accept null key / value. Hashtable is synchronized but hash map is not.
[ October 14, 2005: Message edited by: Srinivasa Raghavan ]
 
Ashwin Kumar
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is correct.

Also note that only one NULL value is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
 
Akshay Kiran
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by AshwinC Kumar:
That is correct.

Also note that only one NULL value is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.


that is however obvious because the keys are implemented in a "Set" and a Set doesn't allow duplicates.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic