手写HashMap

public class MyHashMap<K,V> {

    Node<K,V>[] table;
    class Node<K,V> {
        int hash;
        K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
    //长度
    int size;
    //修改次数
    int modCount;
    //阈值
    int threshold;
    //负载因子
    float loadFactor;

    public MyHashMap() {
        this.loadFactor = 0.75f;
    }

    public V put(K key, V value){
        //hash
        int hash = key.hashCode() ^ key.hashCode() >>> 16;
        //index
        int n = table.length;
        int index = hash % n;
        //table[index] == null -> new node
        if(table[index] == null){
            table[index] = new Node<>(hash, key, value, null);
        }
        //table[index].key == key -> table[index].value = value
        else if(table[index].hash == hash && table[index].key == key){
            table[index].value = value;
        }
        //table[index] instanceof TreeNode -> putTreeVal()
        else if(table[index] instanceof TreeNode){
        }
        //foreach table[index].next
        else {
            //table[index].next.key == key -> table[index].next.value = value
            //table[index].next == null -> table[index].next == new node
            //binCount >= TREEIFY_THRESHOLD - 1 -> treeifyBin(table, hash);
        }
        modCount = modCount + 1;
        size = size + 1;
        if(size > threshold){
            //resize()
        }
        return null;
    }

    public V get(K key){
        //hash
        int hash = key.hashCode() ^ key.hashCode() >>> 16;
        //index
        int n = table.length;
        int index = hash % n;
        //table[index] == null -> return null
        if(table[index] == null){
            return null;
        }
        //table[index].key == key -> return table[index].value
        else if(table[index].hash == hash && table[index].key == key){
            return table[index].value;
        }
        //table[index] instanceof TreeNode -> getTreeNode(key)
        else if(table[index] instanceof TreeNode){
            // return getTreeNode(key);
        }
        //foreach table[index].next
        else {
            //table[index].next.key == key -> return table[index].next.value
            //table[index].next == null -> return null;
        }
        return null;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值