How to Eliminate Duplicate Keys in Hashtable in Java?
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:
- If two objects are equal to the equals() method, then the hashCode() should return the same value for both when called on these objects.
- 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.
- 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
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.
Mrs. Shalini Singhal (12) ==> IT Mr. Kailash Soni (11) ==> CS Mrs. Sunita Gupta (58) ==> IT