Java解决Hash(散列)冲突的四种方法--开放地址法(线性探测,二次探测,伪随机探测)、链地址法、再哈希、建立公共溢出区...

最近时间有点紧,暂时先放参考链接了,待有时间在总结一下:

查了好多,这几篇博客写的真心好,互有优缺点,大家一个一个看就会明白了:

 

参考

1. 先看这个明白拉链法(链地址法),这个带源码,很好看懂,只不过是只讲了拉链法一种;

2. 再看这个比较全的,四种全讲了,链接,这篇比较形象,有图。但是这两篇都没有仔细介绍优缺点;

3. 最后看优缺点,点击这里

转载于:https://www.cnblogs.com/gjmhome/p/11372883.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!以下是使用线性探测和链地址处理冲突创建哈表的Java代码示例: 1. 使用线性探测处理冲突的哈表: ```java class LinearProbingHashTable { private static final int DEFAULT_SIZE = 10; private Entry[] table; private int size; public LinearProbingHashTable() { table = new Entry[DEFAULT_SIZE]; size = 0; } public void put(int key, String value) { Entry entry = new Entry(key, value); int index = hash(key); while (table[index] != null && table[index].getKey() != key) { index = (index + 1) % table.length; // 线性探测 } table[index] = entry; size++; } public String get(int key) { int index = hash(key); while (table[index] != null && table[index].getKey() != key) { index = (index + 1) % table.length; // 线性探测 } if (table[index] != null) { return table[index].getValue(); } return null; } private int hash(int key) { return key % table.length; } private static class Entry { private final int key; private final String value; public Entry(int key, String value) { this.key = key; this.value = value; } public int getKey() { return key; } public String getValue() { return value; } } } ``` 2. 使用链地址处理冲突的哈表: ```java import java.util.LinkedList; class ChainingHashTable { private static final int DEFAULT_SIZE = 10; private LinkedList<Entry>[] table; private int size; public ChainingHashTable() { table = new LinkedList[DEFAULT_SIZE]; size = 0; } public void put(int key, String value) { Entry entry = new Entry(key, value); int index = hash(key); if (table[index] == null) { table[index] = new LinkedList<>(); } LinkedList<Entry> chain = table[index]; for (Entry e : chain) { if (e.getKey() == key) { e.setValue(value); return; } } chain.add(entry); size++; } public String get(int key) { int index = hash(key); if (table[index] != null) { LinkedList<Entry> chain = table[index]; for (Entry e : chain) { if (e.getKey() == key) { return e.getValue(); } } } return null; } private int hash(int key) { return key % table.length; } private static class Entry { private final int key; private String value; public Entry(int key, String value) { this.key = key; this.value = value; } public int getKey() { return key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } ``` 这是创建哈表的基本示例,你可以根据自己的需求进行修改和扩展。望对你有所帮助!如有更多问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值