手写HashMap

今天在做一个笔试题时,竟然要求手写一个HashMap,当场就懵了......

不过话说回来,自己实现的过程中,也能加深对哈希表的理解。

直接上代码。

class MyHashMap{
    static class Node{
        int key;
        String value;
        Node next;
        Node(int _key, String _value){
            key = _key;
            value = _value;
        }
    }

    Node[] nodes = new Node[10010];

    //添加
    public void put(int key, String value){
		//获取存放的位置
        int idx = getIndex(key);
        Node ioc = nodes[idx], tmp = ioc;
        if(ioc != null){
			//如果当前位置已经有值了,用链表存储起来(拉链法)
            Node prev = null;
            while(tmp != null){
                if(tmp.key == key){
                    tmp.value = value;
                    return;
                }
                prev = tmp;
                tmp = tmp.next;
            }
            tmp = prev;
        }

		//存储
        Node node = new Node(key, value);
        if(tmp != null){
            tmp.next = node;
        }else{
            nodes[idx] = node;
        }
    }

    //查找
    public String get(int key){
		//获取存放的位置
        int idx = getIndex(key);
        Node ioc = nodes[idx];
        if(ioc != null){
            while(ioc != null){
				//遍历当前位置的值,找到key相同的数返回
                if(ioc.key == key){
                    return ioc.value;
                }
                ioc = ioc.next;
            }
        }

        return "_EMPTY_";
    }

    //删除
    public void remove(int key){
		//获取存放的位置
        int idx = getIndex(key);
        Node ioc = nodes[idx];
        if(ioc != null){
            Node prev = null;
            while(ioc != null){
				//删除key后,整理当前位置的链表
                if(ioc.key == key){
                    if(prev != null){
                        prev.next = ioc.next;
                    }else{
                        nodes[idx] = ioc.next;
                    }
                    return;
                }
                prev = ioc;
                ioc = ioc.next;
            }
        }
    }

	//根据hash值计算可以存放的位置
    int getIndex(int key){
        int hash = Integer.hashCode(key);
        hash ^= (hash >>> 16);
        return hash % nodes.length;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值