Skip to content
Related Articles

Related Articles

Hashtable Implementation with equals and hashcode Method in Java
  • Last Updated : 28 Jan, 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 hastable 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..");
    }
}
Output
Traversing 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;
    }
}
Output
Traversing 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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :