HashMap如何实现的(手写一个HashMap)

1.原理

在这里插入图片描述

2.代码

Map

package com.mapText;

public interface Map<K,V> {
     V put(K k,V v);
     V get(K k);
     int size();

     interface Entry<K,V>{//创建一个对象,用于装值
         K getKey();
         V getValue();
     }

}

HashMap

package com.mapText;

public class HashMap<K,V> implements Map<K,V> {
    private Entry<K,V> table[]=null;
    int size=0;

    public HashMap() {
        this.table = new Entry[16];
    }


    @Override
    public V put(K k,V v) {
        int index=hash(k);
        Entry<K,V> entry=table[index];
        if(entry==null){
            table[index]=new Entry<K,V>(k,v,index,null);
        }else{
            table[index]=new Entry<K,V>(k,v,index,entry);
        }
        size++;
        return v;
    }

    @Override
    public V get(K k) {
        int index=hash(k);
        if(table[index]==null){
            return null;
        }else{
            return Search(k,table[index]);
        }
    }

    /**
     * 返回map长度
     * @return
     */
    @Override
    public int size() {
        return size;
    }

    /**
     *
     *
     * @param k 查询的k值
     * @param entry 待查询的链表
     * @return
     */
    public V Search(K k,Entry<K,V> entry){
        if(k==entry.key){
            return entry.getValue();
        }else{
            if(entry.entry!=null){
                return Search(k,entry.entry);
            }

        }
        return null;
    }

    /**
     * 获取K的哈希值
     * @param k
     * @return
     */
    private int hash(K k){
        int index=k.hashCode()%16;
        return index>0?index:-index;
    }



    class Entry<K,V> implements Map.Entry<K,V>{

        private K key;
        private V value;
        private int hashcode;
        private Entry<K,V> entry;

        public Entry(K key, V value, int hashcode, Entry<K, V> entry) {
            this.key = key;
            this.value = value;
            this.hashcode = hashcode;
            this.entry = entry;
        }

        @Override
        public K getKey() {
            return this.key;
        }

        @Override
        public V getValue() {
            return this.value;
        }
    }
}

test

package com.mapText;

public class test {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String, String>();
        map.put("11","111");
        map.put("22","222");
        map.put("33","333");
        System.out.println(map.get("11"));
        System.out.println(map.get("22"));
        System.out.println(map.get("33"));
        System.out.println(map.size());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值