📜  Java中使用equals和hashcode方法的Hashtable实现

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

Java中使用equals和hashcode方法的Hashtable实现

要实现哈希表,我们应该使用哈希表类,它将键映射到值。哈希表的键或值应该是非空对象。为了从哈希表中存储和检索数据,用作键的非空对象必须实现hashCode()方法和equals()方法。 Hashtable 以无序和无序的形式产生输出。

示例 1:

在下面的示例中,我们使用 Integer 作为键,使用 Student 对象作为值。为了避免重复键,它实现了 hashCode() 和 equals() 方法。如果我们输入重复键,那么哈希表会自动消除重复键。

Java
// Java Programs to implement hashtable 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 list
            = new Hashtable();
 
        // 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..");
    }
}


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 list
            = new Hashtable();
        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;
    }
}


输出
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

示例 2

在这个哈希表中,字符串作为键,Student 对象作为值。为了避免重复键,它实现了hashCode()equals()方法。如果我们输入重复键,那么哈希表会自动消除重复键

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 list
            = new Hashtable();
        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;
    }
}


输出
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