最简单的哈希算法,哈希算法通俗易懂

首页 > 经验 > 作者:YD1662022-11-18 03:08:01

测试

@Test public void test_hashMap01() { Map<String, String> map = new HashMap01<>(); map.put("01", "花花"); map.put("02", "豆豆"); logger.info("碰撞前 key:{} value:{}", "01", map.get("01")); // 下标碰撞 map.put("09", "蛋蛋"); map.put("12", "苗苗"); logger.info("碰撞前 key:{} value:{}", "01", map.get("01")); }

最简单的哈希算法,哈希算法通俗易懂(5)

06:58:41.691 [main] INFO cn.bugstack.algorithms.test.AlgorithmsTest - 碰撞前 key:01 value:花花 06:58:41.696 [main] INFO cn.bugstack.algorithms.test.AlgorithmsTest - 碰撞前 key:01 value:苗苗 Process finished with exit code 0

2. 拉链寻址

说明:既然我们没法控制元素不碰撞,但我们可以对碰撞后的元素进行管理。比如像 HashMap 中拉链法一样,把碰撞的元素存放到链表上。这里我们就来简化实现一下。

public class HashMap02BySeparateChaining<K, V> implements Map<K, V> { private final LinkedList<Node<K, V>>[] tab = new LinkedList[8]; @Override public void put(K key, V value) { int idx = key.hashCode() & (tab.length - 1); if (tab[idx] == null) { tab[idx] = new LinkedList<>(); tab[idx].add(new Node<>(key, value)); } else { tab[idx].add(new Node<>(key, value)); } } @Override public V get(K key) { int idx = key.hashCode() & (tab.length - 1); for (Node<K, V> kvNode : tab[idx]) { if (key.equals(kvNode.getKey())) { return kvNode.value; } } return null; } static class Node<K, V> { final K key; V value; public Node(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } } }

最简单的哈希算法,哈希算法通俗易懂(6)

测试

@Test public void test_hashMap02() { Map<String, String> map = new HashMap02BySeparateChaining<>(); map.put("01", "花花"); map.put("05", "豆豆"); logger.info("碰撞前 key:{} value:{}", "01", map.get("01")); // 下标碰撞 map.put("09", "蛋蛋"); map.put("12", "苗苗"); logger.info("碰撞前 key:{} value:{}", "01", map.get("01")); }

最简单的哈希算法,哈希算法通俗易懂(7)

07:21:16.654 [main] INFO cn.bugstack.algorithms.test.AlgorithmsTest - 碰撞前 key:01 value:花花 07:22:44.651 [main] INFO cn.bugstack.algorithms.test.AlgorithmsTest - 碰撞前 key:01 value:花花 Process finished with exit code 0

3. 开放寻址

说明:除了对哈希桶上碰撞的索引元素进行拉链存放,还有不引入新的额外的数据结构,只是在哈希桶上存放碰撞元素的方式。它叫开放寻址,也就是 ThreaLocal 中运用斐波那契散列 开放寻址的处理方式。

public class HashMap03ByOpenAddressing<K, V> implements Map<K, V> { private final Node<K, V>[] tab = new Node[8]; @Override public void put(K key, V value) { int idx = key.hashCode() & (tab.length - 1); if (tab[idx] == null) { tab[idx] = new Node<>(key, value); } else { for (int i = idx; i < tab.length; i ) { if (tab[i] == null) { tab[i] = new Node<>(key, value); break; } } } } @Override public V get(K key) { int idx = key.hashCode() & (tab.length - 1); for (int i = idx; i < tab.length; i ){ if (tab[idx] != null && tab[idx].key == key) { return tab[idx].value; } } return null; } static class Node<K, V> { final K key; V value; public Node(K key, V value) { this.key = key; this.value = value; } } }

最简单的哈希算法,哈希算法通俗易懂(8)

上一页12345下一页

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.