Hashtable Implementation with equals and hashcode Method in Java
Last Updated :
20 Sep, 2021
To implement a hash table, we should use the hash table class, which will map keys to the values. The key or values of the hash table should be a non-null object. In order to store and retrieve data from the hash table, the non-null objects, that are used as keys must implement the hashCode() method and the equals() method. Hashtable produces output in unordered and unsorted form.
Example 1:
In the following example, we are using Integer as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter duplicate key then the hashtable eliminates the duplicate keys automatically.
Java
// Java Programs to implement hashtable with
// equals() and hashcode() method
// Importing hashtable and Scanner classes
// from java.util package
import java.util.Hashtable;
import java.util.Scanner;
// Class 1
// Helper class
class Student {
// Initializing the instance variables
// of this class
private int sid;
private String name;
private String mobno;
// Constructor of student class
// to initialize the variable values
public Student(int sid, String name, String mobno)
{
// Super keyword refers to parent object
super();
// This keyword refers to current object
// in a constructor
this.sid = sid;
this.name = name;
this.mobno = mobno;
}
// Method 1
// getter for Sid
public int getSid() { return sid; }
// Method 2
// setter for Sid
public void setSid(int sid) { this.sid = sid; }
// Method 3
// getter for name
public String getName() { return name; }
// Method 4
// setter for name
public void setName(String name) { this.name = name; }
// Method 5
// getter for mobno
public String getMobno() { return mobno; }
// Method 6
// setter for mobno
public void setMobno(String mobno)
{
this.mobno = mobno;
}
// Now, overriding methods
// Overriding of hashCode
// @Override
public int hashCode() { return this.getSid(); }
// Overriding of equals
// @Override
public boolean equals(Object o)
{
if (o instanceof Student) {
return (this.sid) == (((Student)o).sid);
}
return false;
}
// Overriding of toString() method
// @Override
public String toString()
{
return "id=" + sid + ", name=" + name
+ ", mobno=" + mobno;
}
}
// Class 2
// Main class for hashtableExample
public class GFG {
// Main driver method
public static void main(String a[])
{
// Initializing the hashtable with
// key as integer and value as Student object
// Creating an Hashtable object
// Declaring object of Integer and String type
Hashtable<Integer, Student> list
= new Hashtable<Integer, Student>();
// Adding elements to the hashtable
// Custom inputs
list.put(101,
new Student(101, "Ram", "9876543201"));
list.put(102,
new Student(102, "Shyam", "8907685432"));
list.put(103,
new Student(103, "Mohan", "8907896785"));
list.put(104, new Student(104, "Lakshman",
"8909006524"));
list.put(105,
new Student(105, "Raman", "6789054321"));
// Display message
System.out.println("Traversing the hash table");
// Traversing hashtable using for-each loop
for (Student i : list.values()) {
System.out.println(i);
}
// New line
System.out.println();
// Display message
System.out.println(
"Search the student by student id");
// New line
System.out.println();
// Display message
System.out.println("Enter the student id : ");
// Custom value in a variable is assigned
int temp = 104;
// Display message
System.out.println("104");
// Traversing hashtable using for-each loop
for (Student s : list.values()) {
if (s.getSid() == temp) {
// If student found, simply print the
// student details
System.out.println("Student is : " + s);
// Exit the program
System.exit(0);
}
}
// If student not found execute the command
// Print the display message
System.out.println("Student not found..");
}
}
OutputTraversing the hash table
id=105, name=Raman, mobno=6789054321
id=104, name=Lakshman, mobno=8909006524
id=103, name=Mohan, mobno=8907896785
id=102, name=Shyam, mobno=8907685432
id=101, name=Ram, mobno=9876543201
Search the student by student id
Enter the student id :
104
Student is : id=104, name=Lakshman, mobno=8909006524
Example 2
Here in this hashtable, string as keys, and Student object as values. To avoid duplicate keys, it has implemented hashCode() and equals() methods. In case, if we enter the duplicate key then the hashtable eliminates the duplicate keys automatically
Java
// Main class
import java.util.Hashtable;
import java.util.Scanner;
public class HashtableExample2 {
public static void main(String a[])
{
// Initializing the hashtable with
// key as String and values as Student object
Hashtable<String, Student> list
= new Hashtable<String, Student>();
list.put("Ram",
new Student(1, "Ram", "8907654321"));
list.put("Sita",
new Student(2, "Sita", "9809876543"));
list.put("Mohan",
new Student(3, "Mohan", "9098765421"));
list.put("Soham",
new Student(4, "Soham", "7898790678"));
list.put("Lakhan",
new Student(5, "Lakhan", "7890567845"));
// Traversing the hashtable using for-each loop
System.out.println("Traversing the hash table");
for (Student i : list.values()) {
System.out.println(i);
}
System.out.println();
// Search the student using their names
System.out.println(
"Search the student by student id");
System.out.println();
System.out.println("Enter the student id : ");
int temp = 3;
System.out.println("3");
for (Student s : list.values()) {
if (s.getRollno() == temp) {
// If found, then print the student details
System.out.println("Student is : " + s);
// Terminate the program
System.exit(0);
}
}
// If student not found, print that there is no
// student
System.out.println("Student not found..");
}
}
// Student class
class Student {
// Initializing the instance variables
private int rollno;
private String name;
private String mobno;
// Constructor to initialize the values of variables
public Student(int rollno, String name, String mobno)
{
super();
this.rollno = rollno;
this.name = name;
this.mobno = mobno;
}
// getter for roll no
public int getRollno() { return rollno; }
// setter for roll no
public void setRollno(int rollno)
{
this.rollno = rollno;
}
// getter for name
public String getName() { return name; }
// setter for name
public void setName(String name) { this.name = name; }
// getter for mobno
public String getMobno() { return mobno; }
// setter for mobno
public void setMobno(String mobno)
{
this.mobno = mobno;
}
// Overriding of hashCode
@Override public int hashCode()
{
return this.getRollno();
}
// Overriding of equals
// @Override
public boolean equals(Object o)
{
if (o instanceof Student) {
return (this.rollno) == (((Student)o).rollno);
}
return false;
}
// Overriding of toString
@Override public String toString()
{
return "Rollno=" + rollno + ", name=" + name
+ ", mobno=" + mobno;
}
}
OutputTraversing the hash table
Rollno=2, name=Sita, mobno=9809876543
Rollno=3, name=Mohan, mobno=9098765421
Rollno=5, name=Lakhan, mobno=7890567845
Rollno=4, name=Soham, mobno=7898790678
Rollno=1, name=Ram, mobno=8907654321
Search the student by student id
Enter the student id :
3
Student is : Rollno=3, name=Mohan, mobno=9098765421
Similar Reads
Java Program to Implement Hash Tables with Double Hashing Double hashing is a technique in an open addressing scheme. and there is the ordinary hash function. In an open addressing scheme, the actual hash function is taking the ordinary hash function when its space is not empty then it will perform another hash function to get some space to insert. Double
10 min read
How to Implement a Custom Hash function for Keys in a HashMap in Java? In Java, HashMap is the data structure that implements the Map interface. This is used to save the data in the form of key-value pairs. In this article, we will learn how to implement a Custom Hash function for keys in a HashMap in Java. In Java, implementing the custom hash function for keys in a H
2 min read
Java Program to Implement HashTables with Linear Probing Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. Suppose an object is to be assigned a key to it to make searching easy. To store the key/value pair, one can use a simple array like a data structure where keys (integers) can be used directly
5 min read
Java Program to Implement HashTable API The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. To implement Hashtable API f
4 min read
How does HashTable Handle HashCode Distribution in Java? Key-value pairs that are mapped from keys to values using a hash function are stored in Java databases using hash tables. The distribution of hash codes, which guarantees effective element retrieval and storage, is one of a hash table's most important features. In this article, we will learn about h
3 min read