手写一个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; } }}

测试结果

上一篇:[编程题]:0和5组合成最大的能被90整除的数(百度2021)
下一篇:Nginx总结

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年03月25日 17时56分46秒