java自实现hashmap数据结构

Design a HashMap without using any built-in hash table libraries.

Implement the MyHashMap class:

MyHashMap() initializes the object with an empty map. void put(int
key, int value) inserts a (key, value) pair into the HashMap. If the
key already exists in the map, update the corresponding value. int
get(int key) returns the value to which the specified key is mapped,
or -1 if this map contains no mapping for the key. void remove(key)
removes the key and its corresponding value if the map contains the
mapping for the key.
在这里插入图片描述

class MyHashMap {
	//双值存储节点
    private class Pair{
        private int key;
        private int value;

        public Pair() {}

        public Pair(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }

	//设置哈希算法
    private static final int BASE = 888;
    //设链表数组
    private LinkedList[] data;

	//初始化
    public MyHashMap() {
        data = new LinkedList[BASE];
        for (int i = 0; i < BASE; i++) {
            data[i] = new LinkedList<Pair>();
        }
    }

	//哈希函数
    public int hash(int key){return key%BASE;}
    
    //存值
    public void put(int key, int value) {
        int h = hash(key);
        Iterator<Pair> iterator =  data[h].iterator();
        //顺着链表查找,找到就覆盖
        while (iterator.hasNext()){
            Pair pair = iterator.next();
            if (pair.getKey() == key) {
                pair.setValue(value);
                return;
            }
        }
        //找不到,尾部新增
        data[h].offerLast(new Pair(key,value));
    }
    
    //取值
    public int get(int key) {
        int h = hash(key);
        Iterator<Pair> iterator = data[h].iterator();
        while (iterator.hasNext()){
            Pair pair = iterator.next();
            //找到了,就返回
            if (pair.getKey() == key) {
                return pair.getValue();
            }
        }
        //找不到-1
        return -1;
    }
    
    //移除
    public void remove(int key) {
        int h = hash(key);
        Iterator<Pair> iterator = data[h].iterator();
        while (iterator.hasNext()){
            Pair pair = iterator.next();
            //找到了,移除
            if (pair.getKey() == key) {
                data[h].remove(pair);
                return;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值