• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Difference between HashMap and HashTable

February 5, 2013 By j2eereference Leave a Comment

Hashtable vs HashMap in Java

Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair.

Similarities between Hashtable and HashMap in Java

There are lot of similarities between Hashtable and HashMap in Java which is good to know:

1) Both Hashtable and HashMap implements java.util.Map interface.
2) Hashtable and HashMap both are hash based collection and works on principle of hashing.
3) Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.
4) From JDK 4 both Hashtable and HashMap are part of Java collection framework.

Difference between Hashtable and HashMap in Java

Despite being so similar there are some differences between Hashtable and HashMap in Java which separates them completely, let’s know about differences:

1) First and most significant difference between Hashtable and HashMap is that,HashMap is not thread-safe while Hashtable is a thread-safe collection. Thread-safety or thread-safe code in Java refers to code which can safely be used or shared in concurrent or multi-threading environment and they will behave as expected. Any code, class or object which can behave differently from its contract on concurrent environment is not thread-safe.

2) Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable. The HashMap must be externally synchronized rather than relying on the internal synchronized methods.

3) Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

4) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

5) One of HashMap’s subclasses is LinkedHashMap, so in the event that you’d want predictable iteration order, you could easily swap out the HashMap for a LinkedHashMap. This wouldn’t be as easy if you are using Hashtable.

6) The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

HashMap Example:

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets. The following program illustrates HashMap. It maps student names to their total marks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.j2eereference;
 
import java.util.*;
 
class HashMapExample {
public static void main(String args[]) {
HashMap hashmp = new HashMap();
hashmp.put("Ankita", new Integer(87));
hashmp.put("Anita", new Integer(77));
hashmp.put("Anupma", new Integer(67));
hashmp.put("Anjali", new Integer(40));
hashmp.put("Ayushi", new Integer(54));
 
Set set = hashmp.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
 
int marks = ((Integer)hashmp.get("Ankita")).intValue();
hashmp.put("Ankita", new Integer(marks + 10));
 
System.out.println("After Correction Ankita's total Marks: " +
hashmp.get("Ankita"));
}
}

Output

Anita: 77

Anjali: 40

Ayushi: 54

Anupma: 67

Ankita: 87

After Correction Ankita’s total Marks: 97

The program begins by creating a hash map and then adds the mapping of student names to marks. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Take a look, how the correction in marks is made for Ankita. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after Ankita’s mark is updated, the hash map will still contain just one name for Ankita.

HashTable Example:

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

A hash table can only store objects that override the hashCode() and equals() methods that are defined by Object. The hashCode() method must compute and return the hash code for the object.

The following example uses a Hashtable to store the names of students and their marks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.j2eereference;
 
import java.util.*;
 
class HashTableExample {
public static void main(String args[]) {
Hashtable marks = new Hashtable();
Enumeration names;
String str;
int mrk;
marks.put("Ankita", new Integer(87));
marks.put("Anita", new Integer(77));
marks.put("Anupma", new Integer(67));
marks.put("Anjali", new Integer(40));
marks.put("Ayushi", new Integer(54));
 
names = marks.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " +marks.get(str));
}
 
mrk = ((Integer)marks.get("Ankita")).intValue();
marks.put("Ankita", new Integer(mrk+10));
System.out.println("After Correction Ankita's total Marks: " +marks.get("Ankita"));
}
}

Output

Anupma: 67

Anita: 77

Ayushi: 54

Anjali: 40

Ankita: 87

After Correction Ankita’s total Marks: 97

Like the map classes, Hashtable does not directly support iterators. Thus, the above program uses an enumeration to display the marks of students.

Related Posts

  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • What is ThreadLocal in Java ?
  • ArrayList custom Implementation
  • Difference between volatile and synchronized keyword?
  • How to write thread safe code?
  • How to avoid deadlock in java ?

Filed Under: Core Java

Reader Interactions

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.