×

HashMap Vs HashTable

HashMap

HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element.

It is declared as < k ,v >.

HashMap is similar to HashTable, but HashMap is unsynchronized. It follows hashing technique to store the key and value pairs. To use HashMap, we must import the java. Util package.

Syntax

HashMap <k ,v> hashmapname = new HashMap < >( );

Here k and v represent the datatype of key and value pairs.

Example for HashMap Program

HashMap.java

// importing the required packages
// util package is required to implement hashmap 
import java. util. HashMap ;
import java . io . * ;
class HashMap {
  public static void main( String[] args) {
    // create a hashmap
    HashMap < String , Integer> h1  = new HashMap < > ();
    // adding  elements to hashmap
    h1 . put ( " Hi " ,  2);
    h1 . put ( " Hello " ,  3);
    h1 . put ( " Everyone " ,  8);
    System . out. println ( " HashMap is : " + h1);
  } // Main
}//  HashMap

Output

HashMap Vs HashTable

Operations on HashMap

  • Add elements
  • Remove elements
  • Access elements
  • Alter elements

Adding Elements to HashMap

To add elements to HashMap, we use the put ( ) method.

AddElements.java

 import java. util. HashMap;
import java . io . * ;
class AddElements {
  public static void main( String[] args) {
    // Object creation for hashmap with name h
    HashMap < String, Integer> h  = new HashMap < > ();
    // add elements to hashmap
    h . put (" One " , 1);
    h . put (" Two " , 2);
    h . put (" Three " , 3);
    System . out. println("HashMap is : " + h);
  } // Main
} // AddElements

Remove Elements in HashMap

To remove elements in HashMap, we use the remove ( ) method.

RemoveElements.java

import java. util. HashMap;
import java . io . * ;
class RemoveElements {
  public static void main( String[] args) {
    // create a hashmap
    HashMap < String, Integer> h2  = new HashMap < > ();
    // add elements to hashmap
    h2 . put ( " One " , 1);
    h2 . put ( " Two " , 2);
    h2 . put ( " Three " , 3);
    h2 . put ( " Four " , 4);
    System . out. println ( " Before removing elements the HashMap is : " + h2 );
    // removing the element with the key "Two."
    h2 . remove ( "  Two " ) ;
    System . out. println ( " After removing element the HashMap is : "  + h2 ) ;
  } // main
}  // RemoveElements

Output

HashMap Vs HashTable

Access Elements in HashMap

To access the elements in HashMap, we use the get method

AccessElement.java

import java. util. HashMap;
import java . io . * ;
class AccessElement {
  public static void main( String[] args) {
    // create a hashmap
    HashMap < Integer,String>  h3 = new HashMap <> ();
    // add elements to hashmap
    h3 . put(1," One ");
    h3 . put(2," Two ");
    h3 . put(3," Three ");
    h3 . put(4," Four ");
    // Printing the HashMap elements
    System . out. println (" Elements of  the HashMap is : " + h3);
    // Accessing the elements of the HashMap
     String value = h3 . get (3);
     // Printing the value of element at index 3
    System . out . println (" Value at index : " + value);
  } // main
}

Output

HashMap Vs HashTable

Change Elements in HashMap

HashMap is mutable. We can change the data of the HashMap by using replace ( ) method.

AlterElements.java

import java. util. HashMap;
import java . io . * ;
class Alterelements {
  public static void main( String[] args) {
    // create a hashmap
    HashMap < Integer,String> h4  = new HashMap <> ();
    // add elements to hashmap
    h4 . put(1," One ");
    h4 . put(2," Two ");
    h4 . put(3," Three ");
    h4 . put(4," Four ");
    // Printing the HashMap elements
    System . out. println (" Elements of  the HashMap before changing the data is: " + h4);
    // Changing the value of element at index 4 from four to changed
    h4. replace (4," changed ");
    // Printing the Elements of HashMap after altering it
    System . out. println (" Elements of  the HashMap after changing the data is : " + h4); 
  } // Main
} //AlterElements

Output

HashMap Vs HashTable

HashTable

HashTable is the basic implementation of the map interface in Java. HashTable stores the data in key and value pairs. Keys are used to access the value of the element.

It is declared as < k ,v >. It is a synchronised data structure.

Syntax

HashTable <k ,v> hashtablename = new HashTable < >( );

Example for HashTable Program

HashTableExample.java

import java.util.*;  
class HashTableExample{ 
 public static void main(String args[]){  
     // Hashtable declaration
  Hashtable <  String, Integer  > h1 = new Hashtable <  String ,Integer>();  
  // Adding data to Hashtable
  h1 . put ( "Om" , 201  ) ;  
  h1 . put (  "Sai" , 202  ) ;  
  h1 . put ( "Ram", 203  ) ;  
  // Accessing the data of Hashtable
  for( Map . Entry r : h1 . entrySet ( ) ){  
   System . out . println ( r . getKey ( ) + "   " + r . getValue ( ) ) ;  
  }  // for
 }  // main
}  // HashTableExample

Output

HashMap Vs HashTable

Operations on HashMap

  • Add elements
  • Remove elements
  • Access elements

Add Elements to HashTable in Java

To add elements to HashTable, we use the put ( ) method.

AddElements.java

import java .io .*;
import java . util . *;  
class AddElements { 
 public static void main ( String args [ ] ) {  
     // Hashtable declaration
  Hashtable <  String, Integer  > h1 = new Hashtable <  String ,Integer>();  
  // Adding data to Hashtable
  h1 . put ( "Om" , 201  ) ;  
  h1 . put (  "Sai" , 202  ) ;  
  h1 . put ( "Ram", 203  ) ;  
  // Printing the data of Hashtable
   
   System . out . println (h1) ;  
 
 }  // main
}  // AddElements

Output

HashMap Vs HashTable

Remove Elements to HashTable in Java

To add elements to HashTable, we use the remove ( ) method.

RemoveElements.java

import java .io .*;
import java . util . *;  
class RemoveElements { 
 public static void main ( String args [ ] ) {  
     // Hashtable declaration
  Hashtable <  String, Integer  > h1 = new Hashtable <  String ,Integer>();  
  // Adding data to Hashtable
  h1 . put ( "Om" , 201  ) ;  
  h1 . put (  "Sai" , 202  ) ;  
  h1 . put ( "Ram", 203  ) ; 
  // Before removing the element from Hashtable
   System . out . println ("Hashtable  before removing is"+h1) ; 
  // Printing the data of Hashtable
   h1 .remove("Om");
   System . out . println ("After removing element from Hashtable"+h1) ;  
 }  // main
}  // RemoveElements

Output

HashMap Vs HashTable

Access Elements of HashTable in Java

AccessElements.java

import java.util.*;  
class AccessElements{ 
 public static void main(String args[]){  
     // Hashtable declaration
  Hashtable <  String, Integer  > h1 = new Hashtable <  String ,Integer>();  
  // Adding data to Hashtable
  h1 . put ( "Om" , 201  ) ;  
  h1 . put (  "Sai" , 202  ) ;  
  h1 . put ( "Ram", 203  ) ;  
  // Accessing the data of Hashtable
  for( Map . Entry r : h1 . entrySet ( ) ){  
   System . out . println ( r . getKey ( ) + "   " + r . getValue ( ) ) ;  
  }  // for
 }  // main
}  // AccessElemets

Output

HashMap Vs HashTable

Differences between HashMap and HashTable

HashMapHashTable
HashMap does not have synchronisation. Without suitable synchronisation code, it cannot be shared by several threads and is not thread safe.The HashTable is synchronised. It is shared across numerous threads and is thread-safe.
Because multiple threads can run simultaneously, the HashMap object is not thread-safe.The object of the HashTable may only be operated by one thread at a time. It is, therefore, thread-safe.
HashMap supports a single null key as well as multiple null values.Invalid keys and values are not permitted in HashTables.
The lack of waiting time for threads results in high performance.Low-performance results from an increase in the thread's waiting time.
By calling this function, we can make the HashMap synchronised. Map m = Collections.synchronizedMap(hashMap);Internal synchronisation of the HashTable prevents unsynchronization from occurring.
Iterator iterates over HashMap.Enumerator and Iterator iterate through the HashTable.
HashMap derives from the AbstractMap class.The Dictionary class is inherited by HashTable.
The HashMap iterator is reliable.The iterator in a HashTable is not error-proof.
It has no legacy.The legacy is there.

Related Topics

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.