Implementación de tabla hash con iguales y método hashcode en Java

Para implementar una tabla hash, debemos usar la clase de tabla hash, que asignará claves a los valores. La clave o los valores de la tabla hash deben ser un objeto no nulo. Para almacenar y recuperar datos de la tabla hash, los objetos no nulos que se usan como claves deben implementar el método hashCode() y el método equals() . Hashtable produce resultados en forma desordenada y desordenada.

Ejemplo 1: 

En el siguiente ejemplo, usamos Integer como claves y Student object como valores. Para evitar claves duplicadas, ha implementado los métodos hashCode() y equals(). En caso de que ingresemos una clave duplicada, la tabla hash elimina las claves duplicadas automáticamente.

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<Integer, Student> list
            = new Hashtable<Integer, Student>();
 
        // 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..");
    }
}
Producción

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

Ejemplo 2 

Aquí, en esta tabla hash, la string como claves y el objeto Student como valores. Para evitar claves duplicadas, ha implementado los métodos hashCode() y equals() . En caso de que ingresemos la clave duplicada, la tabla hash elimina las claves duplicadas automáticamente

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<String, Student> list
            = new Hashtable<String, Student>();
        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;
    }
}
Producción

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

Publicación traducida automáticamente

Artículo escrito por snigdha_yambadwar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *