尝试自定义HashMap

package cn.itcast;

public class MyMap01 {
    private Node[] table;

    public MyMap01(){
        this.table = new Node[16];
    }
    public void put(Object key,Object value){
        int hash = MyHash(key);
        Node newnode = new Node(key, value, hash);

        Node linked = table[hash];
        if(linked == null){
            table[hash]=newnode;
        }else{
            while(linked!=null){
                if(linked.getKey().equals(key)){
                    linked.setValue(value);
                }else{
                    if(linked.getNext()==null){
                        linked.setNext(newnode);
                    }
                }
                linked=linked.getNext();
            }
        }
    }
    public Object get(Object key){
        int hash = MyHash(key);
        Node linked = table[hash];
        if (linked == null)throw new RuntimeException("key 不存在: "+key);
        while(!key.equals(linked.getKey())){
            linked=linked.getNext();
        }
        return linked.getValue();
    }
    public int MyHash(Object key){
        int hashCode = key.hashCode();
        int hash = hashCode & (this.table.length - 1);
        System.out.println(hash);
        return hash;
    }

    public static void main(String[] args) {
        MyMap01 myMap = new MyMap01();
        myMap.put(10,"aa");
        myMap.put(20,"bb");
        myMap.put(30,"cc");
        myMap.put(30,"dd");
        myMap.put(40,"66666");
        myMap.put(90,"66666");

        System.out.println(myMap.get(30));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值