×

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

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.