📜  Java中如何消除Hashtable中的重复键?

📅  最后修改于: 2022-05-13 01:54:22.148000             🧑  作者: Mango

Java中如何消除Hashtable中的重复键?

HashTable 类是Java中 Collection 框架的一部分,它与 HashMap 的唯一主要区别是它是同步的。哈希表将键映射到值,即它在内部使用桶来存储键值对,键值对的对应桶由键的哈希码确定。在使用哈希表时,我们指定用作键的任何对象以及我们想要链接到该键的任何值。任何非空对象都可以用作键。

概念: hashCode() 方法

在覆盖 hashCode() 方法时,有一些事情需要注意,如下所示:

  1. 如果两个对象与 equals() 方法相等,则在对这些对象调用时,hashCode() 应为两者返回相同的值。
  2. 尽管对于根据 equals() 方法被认为不相等的对象, hashCode() 没有必要总是返回不同的值,但应该记住,有最小的冲突。
  3. 每当在程序中的任何时间实例对同一对象调用 hashCode() 方法时,它都应返回相同的值。

方法:为了使用任何用户定义的对象作为键,其对应的类应该实现 hashCode() 方法和 equals() 方法。由于哈希表使用这些方法成功地存储和检索条目。

实现:让我们随机创建一个子类来演示命名的教师类。它包含教师 id教师姓名。在这里,没有两个或两个以上的老师可以有相同的 id,但他们可以有相同的名字。我们将在Teacher 类的equals()方法中实现这个逻辑。这个例子显示了用户定义的对象可以用作哈希表中的键,并且可以避免任何重复的键。

示例 1:子类 |教师班

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 + ")";
    }
}


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 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 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));
        }
    }
}


示例 2:创建驱动程序类

创建包含存储键值对的哈希表的驱动程序类。在这里,forsake 如示例 1 所示 - 部门名称将存储为该特定教师的值。

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 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 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));
        }
    }
}

输出:

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