How to Eliminate Duplicate Keys in Hashtable in Java?
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:
- 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
Java
// 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 + ")";
}
}
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
// 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));
}
}
}
Output:
Mrs. Shalini Singhal (12) ==> IT
Mr. Kailash Soni (11) ==> CS
Mrs. Sunita Gupta (58) ==> IT
Similar Reads
How to find duplicate elements in a Stream in Java Given a stream containing some elements, the task is to find the duplicate elements in this stream in Java. Examples: Input: Stream = {5, 13, 4, 21, 13, 27, 2, 59, 59, 34} Output: [59, 13] Explanation: The only duplicate elements in the given stream are 59 and 13. Input: Stream = {5, 13, 4, 21, 27,
5 min read
How does TreeMap Handle Duplicate Keys in Java ? In Java, when it comes to handling duplicate keys in a TreeMap, the class does not allow duplicate keys. If we try to insert a key-value pair with a key that already exists in the TreeMap, the new value will override the existing one associated with that key. Declaration of a TreeMap:TreeMap<KeyT
2 min read
How to Create a Synchronized HashTable in Java? In Java, a synchronized HashTable is achieved by wrapping a regular HashTable with the Collection.synchronizedMap( ) method. This wrapper ensures that each method of the Map interface is synchronized, making the HashTable thread-safe. Syntax:Map<KeyType, ValueType> synchronizedHashTable = Coll
3 min read
How to Use Enumeration to Display Elements of Hashtable in Java? 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. Now here we can get the keys and
2 min read
How to Eliminate Duplicate User Defined Objects from LinkedHashSet in Java? While creating a HashSet of your own class, always ensure that the HashCode() method of the key of HashSet doesnât change. Java Object hashCode() is a native method and returns the integer hash code value of the object. If two objects are equal according to the equals() method, then their hash code
3 min read