Java手写简易版HashMap

2022-07-27,,,

很粗糙,比起源码还是少了很多的

接口

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

public class HashMap<K,V> implements Map<K,V> {
    private Entry<K,V>[] table=null;
    int size=0;
    public HashMap(){
        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);
        }
        //数组这个位置已有值,jdk8之前,头插法
        else{
            table[index]=new Entry<K,V>(k,v,index, entry);
        }
        size++;
        return table[index].getValue();
    }

    private int hash(K k){
        int i=k.hashCode()%16;
        return Math.abs(i);
    }

    private Entry findValue(K k,Entry<K,V> entry){
        if(entry.getKey().equals(k)||entry.getKey()==k){
            return entry;
        }
        else{
            if(entry.next!=null){
                findValue(k,entry.next);
            }
        }
        return null;
    }

/*
判断是否有值,没有值返回空
有值,key相等,返回
不相等,判断next是否为空
不为空,判断key是否相等,返回
 */
    @Override
    public V get(K k) {
        if(size==0)
            return null;
        int index=hash(k);
        if(null==table[index])
            return null;
        Entry<K,V> entry=table[index];
        entry=findValue(k,entry);
        if(entry!=null)
            return entry.getValue();
        return null;
    }

    @Override
    public int size() {
        return size;
    }

    class Entry<K,V> implements Map.Entry<K,V>{
        K k;
        V v;
        int hash;
        Entry<K,V> next;

        public Entry(K k, V v, int hash, Entry<K,V> next) {
            this.k=k;
            this.v=v;
            this.hash=hash;
            this.next=next;
        }

        @Override
        public K getKey() {
            return k;
        }

        @Override
        public V getValue() {
            return v;
        }
    }
}

测试类

public class test1 {
    public static void main(String[] args) {
       HashMap<String,String> map=new HashMap<>();
       map.put("陈官鸿","宝岛甜心");
       map.put("王俊凯","tfboys");
       System.out.println(map.get("陈官鸿"));
       System.out.println(map.get("刘耀元"));
    }
}

测试结果

本文地址:https://blog.csdn.net/weixin_42970433/article/details/109639772

《Java手写简易版HashMap.doc》

下载本文的Word格式文档,以方便收藏与打印。