栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java自实现hashmap数据结构

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
        }
    }

	//哈希函数
    public int hash(int key){return key%base;}
    
    //存值
    public void put(int key, int value) {
        int h = hash(key);
        Iterator 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 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 iterator = data[h].iterator();
        while (iterator.hasNext()){
            Pair pair = iterator.next();
            //找到了,移除
            if (pair.getKey() == key) {
                data[h].remove(pair);
                return;
            }
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713128.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号