Data structure - hash table

Posted by nblackwood on Fri, 24 Dec 2021 08:27:06 +0100

1, HashSet, HashMap, HashTable

First, set represents the unordered elements of the set. Duplicate elements are not allowed in the set
Map represents a set composed of multiple key values. Map set is an extension of set set

Based on hashing principle, HashMap stores and obtains objects through put() and get() methods.

  1. Create a HashMap
    Map<String, Integer> Ages = new HashMap<String, Integer>();
  2. put() method
    put(key, value) establishes a mapping relationship between the key and the value. If the key is stored for the first time, it directly stores the element and returns null; If the key does not exist for the first time, replace the previous value with a value and return the previous value
  3. get() method
    get(Object key) returns the value of the key mapping. If the key has no mapping value, null is returned

Other methods for HashMap are as follows:

Differences between HashMap and HashTable

Both HashMap and Hashtable implement the Map interface. The main differences are: thread safety, synchronization, and speed. HashMap is almost equivalent to Hashtable, except that HashMap is non synchronized and can accept null(HashMap can accept null key and value, while Hashtable cannot).

HashMap is not synchronized, while Hashtable is synchronized, which means that Hashtable is thread safe and multiple threads can share a Hashtable; Multiple threads cannot share HashMap.

Differences between HashMap and HashSet

HashSet implements the Set interface, which does not allow duplicate values in the Set. HashMap implements the Map interface, which maps key value pairs.
HashSet extends HashMap, so map storage is still used at the bottom. The storage implementation is consistent with map. HashMap stores key values and HashSet stores objects.

Two, simulated hash table

Introduction to hash table

Hash table (also known as hash table) is a data structure that is accessed directly according to the key value. That is, it accesses records by mapping key values to a location in the table to speed up the search. This mapping function is called a hash function, and the array of records is called a hash table.

Simulation topic

Google computer questions

1) There is a company,When new employees come to report,The employee's information is required to be added(id,Gender,Age,address..),
When entering the employee's id Time,It is required to find all the information of the employee.
2) requirement: Do not use database,Try to save memory,The faster the better=>Hashtable (hash)

Implementation idea:

The code is as follows:

package com.tunan.hashtable;

import java.util.Scanner;

public class HashTableDemo {

	public static void main(String[] args) {
		//test
		//Create hashtable
		HashTable hashTable = new HashTable(7);
		//Simple menu
		String key = "";
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.println("add:add to");
			System.out.println("list:display");
			System.out.println("find:lookup");
			System.out.println("exit:sign out");
			
			key = scanner.next();
			switch (key) {
			case "add":
				System.out.println("Please enter id");
				int id = scanner.nextInt();
				System.out.println("Please enter a name");
				String name = scanner.next();
				Emp emp = new Emp(id, name);
				hashTable.add(emp);
				break;
			case "list":
				hashTable.list();
				break;
			case "find":
				System.out.println("Please enter the to find id");
				id = scanner.nextInt();
				hashTable.findEmpById(id);
				break;
			case "exit":
				scanner.close();
				System.out.println("Exit successful");
				System.exit(0);

			default:
				break;
			}
		}

	}

}

//Create a HashTable to manage multiple linked lists
class HashTable{
	private EmpLinkedList[] empLinkedListArray;
	private int size;//Indicates how many linked lists there are
	
	//constructor 
	public HashTable(int size){
		this.size = size;
		//Initialize empLinkedListArray
		empLinkedListArray = new EmpLinkedList[size];
		
		//Keep one?
		//Don't forget to initialize each linked list
		for(int i = 0; i < size; i++){
			empLinkedListArray[i] = new EmpLinkedList();
		}
	}
	
	//Add employee
	public void add(Emp emp) {
		//According to the employee id, get which linked list the employee should join	
		int empLinkedListNo = hashFun(emp.id);
		//Add emp to the linked list for
		empLinkedListArray[empLinkedListNo].add(emp); 
	}
	
	//Traverse all employees (linked list)
	public void list() {
		for(int i = 0; i < size; i++){
			empLinkedListArray[i].list(i);
		}
	}
	
	//Find employees by id
	public void findEmpById(int id) {
		int empLinkedListNo = hashFun(id);
		Emp emp = empLinkedListArray[empLinkedListNo].findEmpById(id);
		if(emp != null) {
			System.out.printf("In the first%d The employee was found in the linked list id=%d\n", (empLinkedListNo+1), id);
		}else{
			System.out.println("The employee was not found");
		}
	}
	
	//Write hash functions, using a simple modular method
	public int hashFun(int id) {
		return id % size;
	}
}




//Employee's class
class Emp{
	public int id;
	public String name;
	public Emp next;
	//Constructor, next is null by default 
	public Emp(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	
}

//Create an EmpLinkedList to represent a linked list
class EmpLinkedList {
	//The header pointer executes the first Emp, so the head of the linked list directly points to the first employee
	private Emp head;//Default null
	
	//Add employee
	public void add(Emp emp) {
		//If you add the first
		if(head == null) {
			head = emp;
			return;
		}
		//If it is not the first employee, it is traversed
		Emp curEmp = head;
		while(true) {
			if(curEmp.next == null) {
				break;
			}
			curEmp = curEmp.next;	
		}
		//When exiting while, put the node to be added last
		curEmp.next = emp;
	}
	
	//Traversal linked list
	public void list(int no){
		if(head == null) {
			System.out.println("The first"+(no+1)+"The linked list is empty");
			return;
		}
		System.out.print("The first"+(no+1)+"The linked list is:");
		Emp curEmp = head;
		while(true) {
			System.out.printf("=> id=%d name=%s\t", curEmp.id, curEmp.name);
			if(curEmp.next == null) {
				break;
			}
			curEmp = curEmp.next;	
		}
		System.out.println();
	}
	
	//Find employee information by id
	public Emp findEmpById(int id){
		//First judge whether the current is empty
		if(head == null) {
			System.out.println("The linked list is empty");
			return null;
		}
		//ergodic
		Emp curEmp = head;
		while(true) {
			if(curEmp.id == id) {
				break;
			}
			
			//Exit condition
			if(curEmp.next == null){
				curEmp = null;
				break;
			}
			curEmp = curEmp.next;
		}
		return curEmp;
	}
}

Topics: Java data structure HashTable