数据结构和算法:哈希表

哈希表(Hash Table)是一种非常重要的数据结构,它利用哈希函数将键(Key)映射到存储桶(Bucket)的位置,从而实现快速的插入、查找和删除操作。在Java中,哈希表通常由HashMap类实现。

以下是一个简单的哈希表实现,仅用于教学目的,不建议在生产环境中使用。

首先,定义一个哈希函数,它可以根据键计算哈希值:

java 复制代码
public class HashTable {
    private static final int DEFAULT_CAPACITY = 16;
    private int capacity;
    private List<LinkedList<KeyValuePair>> buckets;

    // 简单的哈希函数
    private int hash(int key) {
        return key % capacity;
    }

    // 键值对类
    private static class KeyValuePair {
        int key;
        Object value;

        KeyValuePair(int key, Object value) {
            this.key = key;
            this.value = value;
        }
    }

    public HashTable() {
        this(DEFAULT_CAPACITY);
    }

    public HashTable(int capacity) {
        this.capacity = capacity;
        buckets = new ArrayList<>(capacity);
        for (int i = 0; i < capacity; i++) {
            buckets.add(new LinkedList<>());
        }
    }
}

然后,我们可以实现插入、查找和删除操作:

java 复制代码
public class HashTable {
    // ... 省略之前的代码 ...

    // 插入键值对
    public void put(int key, Object value) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        for (KeyValuePair pair : bucket) {
            if (pair.key == key) {
                pair.value = value; // 更新值
                return;
            }
        }
        bucket.add(new KeyValuePair(key, value)); // 插入新的键值对
    }

    // 获取键对应的值
    public Object get(int key) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        for (KeyValuePair pair : bucket) {
            if (pair.key == key) {
                return pair.value;
            }
        }
        return null; // 未找到键
    }

    // 删除键值对
    public void remove(int key) {
        int index = hash(key);
        LinkedList<KeyValuePair> bucket = buckets.get(index);
        Iterator<KeyValuePair> iterator = bucket.iterator();
        while (iterator.hasNext()) {
            KeyValuePair pair = iterator.next();
            if (pair.key == key) {
                iterator.remove(); // 删除键值对
                return;
            }
        }
    }
}

注意:

  1. 这个实现使用了简单的取模运算作为哈希函数,但在实际中,哈希函数的设计要复杂得多,需要考虑哈希冲突的解决、哈希分布的均匀性等问题。
  2. 当哈希表中的元素过多时,可能会导致哈希冲突加剧,影响性能。此时,可以通过重新分配更大的空间并重新哈希所有元素来解决这个问题,这通常被称为"扩容"或"再哈希"。
  3. Java中的HashMap类使用了更复杂的数据结构和算法,包括链表和红黑树来解决哈希冲突和保持性能。这个简单的哈希表实现仅用于教学目的,无法与HashMap的性能和功能相比。
相关推荐
人道领域14 分钟前
AI抢人大战:谁在收割你的红包
大数据·人工智能·算法
TracyCoder12332 分钟前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
A尘埃32 分钟前
电信运营商用户分群与精准运营(K-Means聚类)
算法·kmeans·聚类
power 雀儿1 小时前
掩码(Mask)机制 结合 多头自注意力函数
算法
会叫的恐龙2 小时前
C++ 核心知识点汇总(第六日)(字符串)
c++·算法·字符串
小糯米6012 小时前
C++顺序表和vector
开发语言·c++·算法
We་ct2 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
Lionel6892 小时前
分步实现 Flutter 鸿蒙轮播图核心功能(搜索框 + 指示灯)
算法·图搜索算法
小妖6662 小时前
js 实现快速排序算法
数据结构·算法·排序算法
xsyaaaan2 小时前
代码随想录Day30动态规划:背包问题二维_背包问题一维_416分割等和子集
算法·动态规划