Skip to content
Related Articles

Related Articles

How to Eliminate Duplicate Keys in Hashtable in Java?
  • Difficulty Level : Medium
  • Last Updated : 13 Jan, 2021

HashTable class is part of the Collection framework in Java where the only major difference it has from HashMap is that it’s synchronized. Hash table maps keys to values i.e. it internally uses buckets to store key-value pairs and the corresponding bucket to a key-value pair is determined by the key’s hash code. While using a Hash table we specify any object which is used as a key and any value which we want to link to that key. Any non-null object can be used as a key.

Concept: hashCode() method

There are certain things to be kept alarmed while overriding the hashCode() method which is as follows:

  1. If two objects are equal to the equals() method, then the hashCode() should return the same value for both when called on these objects.
  2. Although it’s not necessary that the hashCode() should always return distinct value for the objects which are not considered equal according to the equals() method, it should be kept in mind that there are minimal collisions.
  3. Whenever the hashCode() method is called on the same object at any instance of time in the program, it should return the same value.

Method: In order to use any user-defined object as a key, its corresponding class should implement the hashCode() method and the equals() method. Since the hash table uses these methods to successfully store and retrieve the entries.

Implementation: Let us create a subclass be it random to demonstrate named Teacher class. It contains the teacher id and teacher name. Here, no two or more teachers can have the same id, but they may have the same name. This logic we will implement in the equals() method of the Teacher class. This example shows user-defined objects can be used as keys in the Hash table and can avoid any duplicate keys.



Example 1: Subclass | Teacher class

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Sub-class
public class Teacher {
  
    // Member variables
    private int id;
    private String name;
  
    // Constructor
    public Teacher(int id, String name)
    {
        // This keyword to refer current object
        this.id = id;
        this.name = name;
    }
  
    // Remember : Can create own logic and implement
    // that in this method,but here
  
    // Supposed to use the already defined logic
    // which uses the "id" to generate a hash
  
    // Override hash code
    @Override public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }
  
    // Overriding the equals method
    // to compare the equality of two objects
    @Override public boolean equals(Object obj)
    {
        // Step 1: Checking whether its a same object
        if (this == obj)
            return true;
  
        // Step 2: Checking whether the object is null
        if (obj == null)
            return false;
  
        // Step 3: Checking the instance of the object
        // here we can also use the instance of operator
        if (getClass() != obj.getClass())
            return false;
  
        // Step 4:  If the two objects do not have the
        // same "id" then they are treated as unequal
        // objects
        Teacher other = (Teacher)obj;
        if (id != other.id)
            return false;
        return true;
    }
  
    // overriding toString()
    // to print the Teacher detail
    @Override public String toString()
    {
        return name + " (" + id + ")";
    }
}

chevron_right


Example 2: Creating a driver class

Creating a driver class that contains a Hash table that stores the key-value pair. Here, forsake as demonstrated in example 1- department name will be stored as a value of that particular teacher. 

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Driver class 
  
// Importing Hashtable and Set class from
// java.util package
import java.util.Hashtable;
import java.util.Set;
  
public class Gfg {
  
    // Main driver method
    public static void main(String args[])
    {
  
        // Creating a Hashtable object with key and value
        // key of type Teacher and
        // corresponding value of type string
        Hashtable<Teacher, String> table
            = new Hashtable<>();
  
        // Adding value to the hash table object
        // Custom inputs (4 inputs here)
        table.put(new Teacher(12, "Mrs. Shalini Singhal"),
                  "IT");
        table.put(new Teacher(58, "Mrs. Sunita Gupta"),
                  "IT");
        table.put(new Teacher(11, "Mr. Kailash Soni"),
                  "CS");
        // adding duplicate key
        table.put(new Teacher(12, "Mrs. Shalini Singhal"),
                  "IT");
  
        // Printing all the values
        // from the table creating a set of keys
  
        // Retrieving the keys from the keyset() method
        Set<Teacher> keys = table.keySet();
  
        // For-each loop to traverse and print
        // all the correspondong values
        for (Teacher t : keys) {
  
            // Printing all values from table from above
            // retrieved keys
            System.out.println(t + " ==> " + table.get(t));
        }
    }
}

chevron_right


Output:

Mrs. Shalini Singhal (12) ==> IT
Mr. Kailash Soni (11) ==>  CS
Mrs. Sunita Gupta (58) ==>  IT

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :