
手写一个HashMap
发布日期:2021-05-06 22:53:16
浏览次数:22
分类:技术文章
本文共 1652 字,大约阅读时间需要 5 分钟。
手写一个HashMap
根据JDK中HashMap的实现原理,手写一个类似的HashMap.
代码
public class MyHashMap{ private int capacity; private Node [] table; public MyHashMap () { this.capacity = 16; this.table = new Node[capacity]; } public MyHashMap (int capacity) { this.capacity = capacity; this.table = new Node[capacity]; } public void put(K key, V value) { int hashCode = key.hashCode(); int index = hashCode % capacity; Node node = new Node<>(key, value); if (table[index] == null) { table[index] = node; } else { Node cur = table[index]; while (cur.next != null) cur = cur.next; cur.next = node; } } public V get(K key) { int hashCode = key.hashCode(); int index = hashCode % capacity; Node cur = table[index]; if (cur == null) return null; else { while (cur != null && !cur.key.equals(key)) cur = cur.next; if (cur == null) return null; else return cur.value; } } public static void main(String[] args) { MyHashMap map = new MyHashMap<>(5); map.put("key1", 100); map.put("key2", 200); map.put("key3", 300); map.put("key4", 400); map.put("key5", 500); map.put("key6", 600); int res1 = map.get("key1"); System.out.println(res1); int res6 = map.get("key6"); System.out.println(res6); } static class Node { K key; V value; Node next; public Node(K key, V value) { this.key = key; this.value = value; this.next = null; } }}
测试结果

发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2025年03月25日 17时56分46秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
使用开源可视化工具来理解你的 Python 代码 | Linux 中国
2019-03-03
硬核观察 | 有人在比特币骗局中损失了 10 个比特币
2019-03-03
使用 top 命令了解 Fedora 的内存使用情况 | Linux 中国
2019-03-03
8皇后问题 递归 函数调用是重点
2019-03-03
1541 +1 *2 ²
2019-03-03
面试别慌!阿里专家带你从【入门+基础+进阶+项目】攻破SpringBoot
2019-03-03
【Java面试】30个 Java 集合面试必备的问题和答案
2019-03-03
华为鸿蒙到底是不是安卓系统套了个壳?
2019-03-03
fragment中recyclerview的重新加载问题
2019-03-03
window程序设计(1):第一个windows程序
2019-03-03
windows程序设计(4):文本输出
2019-03-03
21.2.3总结
2019-03-03
线性代数和数学期望杂题
2019-03-03
【SSL_P2876】2017年东莞市信息学特长生测试题 工程
2019-03-03
【洛谷_P1433】吃奶酪
2019-03-03
volatile关键字和AtomicInteger
2019-03-03
redisTemplate.opsForHash()
2019-03-03
maven生命周期
2019-03-03
方法的绑定机制-静态绑定和动态绑定
2019-03-03