首页 > 编程语言 >Java数据结构与算法(散列表)

Java数据结构与算法(散列表)

时间:2024-05-29 20:29:40浏览次数:13  
标签:index Java value 列表 return key table 数据结构 size

前言

散列表是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。而key的冲突主要通过链表的方式来处理,后期链表过长情况下可以通过红黑树来优化查询效率。

实现原理

  1. 散列函数(Hash Function): 散列函数用于将输入的键转换为表中的索引。理想的散列函数应当将键均匀地分布到表的各个位置,以减少冲突。散列函数的一些常见实现包括将键的ASCII值进行某种数学运算或使用更复杂的算法,如SHA-256。

  2. 冲突(Collision): 当两个不同的键通过散列函数映射到相同的位置时,就会发生冲突。处理冲突是散列表实现中的一个关键问题。

动画过程

Open Hashing Visualization

具体代码实现

import java.util.LinkedList;

public class HashTable<K, V> {
    // Node class to store key-value pairs
    private static class Node<K, V> {
        K key;
        V value;

        Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    // Default size of the hash table
    private static final int DEFAULT_SIZE = 16;

    // Array of linked lists to store the chains
    private LinkedList<Node<K, V>>[] table;

    // Current size of the hash table
    private int size;

    // Constructor to initialize the hash table with default size
    @SuppressWarnings("unchecked")
    public HashTable() {
        table = new LinkedList[DEFAULT_SIZE];
        size = 0;
    }

    // Hash function to compute index for a key
    private int hash(K key) {
        return Math.abs(key.hashCode() % table.length);
    }

    // Method to insert a key-value pair into the hash table
    public void insert(K key, V value) {
        int index = hash(key);
        if (table[index] == null) {
            table[index] = new LinkedList<>();
        }

        // Check if the key already exists, update value if it does
        for (Node<K, V> node : table[index]) {
            if (node.key.equals(key)) {
                node.value = value;
                return;
            }
        }

        // If key does not exist, add a new node to the chain
        table[index].add(new Node<>(key, value));
        size++;
    }

    // Method to retrieve a value by its key
    public V get(K key) {
        int index = hash(key);
        if (table[index] == null) {
            return null;
        }

        // Search for the key in the chain
        for (Node<K, V> node : table[index]) {
            if (node.key.equals(key)) {
                return node.value;
            }
        }

        // If key is not found, return null
        return null;
    }

    // Method to delete a key-value pair from the hash table
    public boolean delete(K key) {
        int index = hash(key);
        if (table[index] == null) {
            return false;
        }

        // Search for the key in the chain and remove it
        for (Node<K, V> node : table[index]) {
            if (node.key.equals(key)) {
                table[index].remove(node);
                size--;
                return true;
            }
        }

        return false;
    }

    // Method to get the current size of the hash table
    public int size() {
        return size;
    }

    // Method to check if the hash table is empty
    public boolean isEmpty() {
        return size == 0;
    }

    // Main method for testing
    public static void main(String[] args) {
        HashTable<String, Integer> hashTable = new HashTable<>();
        hashTable.insert("apple", 1);
        hashTable.insert("banana", 2);
        hashTable.insert("cherry", 3);

        System.out.println("Value for 'apple': " + hashTable.get("apple"));
        System.out.println("Value for 'banana': " + hashTable.get("banana"));
        System.out.println("Value for 'cherry': " + hashTable.get("cherry"));

        hashTable.delete("banana");
        System.out.println("Value for 'banana' after deletion: " + hashTable.get("banana"));

        System.out.println("Current size: " + hashTable.size());
    }
}

QA:待定

标签:index,Java,value,列表,return,key,table,数据结构,size
From: https://blog.csdn.net/acuteeagle01/article/details/139278438

相关文章

  • Java数据结构与算法(B+树)
    前言B+树(B+Tree)是一种平衡树数据结构,广泛用于数据库和文件系统中。它是一种自平衡的树结构,每个节点包含多个键,并且所有键都是排序的。B+树的叶子节点包含指向相邻叶子节点的指针,这使得范围查询非常高效。B+树的优点1.由于B+树在非叶子结点上不包含真正的数据,只当做索引使用......
  • Erroe:JSON parse error: Cannot deserialize value of type `java.lang.Integer` from
    报错:JSONparseerror:Cannotdeserializevalueoftype`java.lang.Integer`fromObjectvalue(token`JsonToken.START_OBJECT`);nestedexceptioniscom.fasterxml.jackson.databind.exc.MismatchedInputException:Cannotdeserializevalueoftype`java.lang.I......
  • 【python数据结构4】基于栈结构的简单括号匹配
    我们现在把注意力转向使用栈解决真正的计算机问题。你会这么写算术表达式(5+6)*(7+8)/(4+3)其中括号用于命令操作的执行。你可能也有一些语言的经验,如Lisp的构造(defunsquare(n)(*nn))这段代码定义了一个名为square的函数,它将返回参数的n的平方。Lisp......
  • Java项目:205Springboot + vue实现的养老院管理系统(含论文)
    作者主页:夜未央5788 简介:Java领域优质创作者、Java项目、学习资料、技术互助文末获取源码项目介绍基于Springboot+vue实现的养老院管理系统系统包含老人、家属、管理员三个角色系统包含登录、注册、主页、老人管理、家属管理、家属意见管理、寝室管理、老人事故信......
  • 《用ChatGPT轻松搞定Java编程难题:从基础到复杂案例的全面解析》
    ChatGPT国内使用体验点击(文件中并非网站跳转而是详细教程):Docshttps://uajqbcov4oa.feishu.cn/docx/GmeGdznJkoc3nzxHECQcojZ9nXg?from=from_copylink随着人工智能技术的快速发展,越来越多的开发者开始使用ChatGPT来辅助解决编程中的问题。ChatGPT不仅可以快速生成代码,还能进行......
  • java基础
    1.类的概念包:一些接口和类集合在一起,方便使用,类似c语言的头文件使用import关键词,将所用的包导入类:【修饰符】class类名{类体}类中包含构造函数 ,对象(变量),方法等在一个程序中,只有一个pubic类,有一个主类中有main接口,是主程序的接口进入类,用来写一整块的功能【修饰符】包......
  • 升鲜宝供应链管理系统重构版发布(技术点:Java8、mysql8.0 uniapp、vue、android、web 框
    升鲜宝供应链管理系统重构版发布(技术点:Java8、mysql8.0uniapp、vue、android、web框架:Vue3+SpringBoot3),界面功能(三) 主要功能要点:     权限管理(组织机构、用户管理、角色管理、岗位管理)     系统设置(菜单管理、参数管理、数据字典、定时任务、文件管......
  • javascript引入了不同版本的多个jquery,如何不同版本之间不互相影响
    1️⃣ 原因  由于是一个比较老的项目,所以在做功能时,用到了老项目的一个控件,这一个控件是以前封装好的,依赖的是jquery-1.6.min.js。但是在做下拉框多选功能时,在网上找了一个下拉框多选的框架,但是这个框架依赖是jquery.js(3.7.1),所以才出现了这个问题。  简单来说就是新老控件......
  • 添砖Java(十二)——异常,异常捕获,常见异常方法
    异常:定义:异常通俗来讲,其实就是你写出bug来了,编译器给你报错了。publicstaticvoidmain(String[]args)throwsException{intz=10/0;} 这个代码虽然说是可以运行,但是编译器会报错。因为10不能去除以0。异常分为两种,一种是运行时异常,另一种时编译时......
  • javascript右键菜单
      文章来源:https://segmentfault.com/a/1190000023098787 HTML<h1>Clickonblanktoshowcustomcontextmenus</h1>CSS.custom-context-menu{position:fixed;border:1pxsolid#ccc;list-style:none;padding:4px0;border-radius:......