What is the HashTable.equals() method in Java?

The equals() method of HashTable is used to check the equality between two HashTable objects. It is available under the java.util package.

Syntax

HashTable.equals(parameter);

Parameter

This method takes a single object to compare with any HashTable.

Return value

The method returns true if the HashTable is the same as the given object. Otherwise, it returns false.

Code

Let’s have a look at the code.

import java.util.*;
class Solution1 {
public static void main(String args[]) {
// create two hash tables
Hashtable<Integer,String> table1 = new Hashtable<Integer,String>();
Hashtable<Integer,String> table2 = new Hashtable<Integer,String>();
// put values in two tables
table1.put(1, "A");
table1.put(2, "B");
table1.put(3, "C");
table1.put(4, "D");
table2.put(1, "A");
table2.put(2, "B");
table2.put(3, "C");
table2.put(4, "D");
// display result
System.out.println("Are two tables equal:"+table1.equals(table2));
}
}

Explanation

  • In line 1, we import the java.util.* classes to include the HashSet data structure.
  • In lines 7 and 8, we initiate the objects table1 and table2
  • In lines 11 to 14, we insert some key-value pairs in table1.
  • In lines 16 to 19, we insert some key-value pairs in table2.
  • In line 22, we check if table2 is equal to table1 or not, and print the result.