【HashMap】手写一个简易的hashMap

手写一个简易的hashMap,包含put、set和size功能(数组+链表)

Java code


/**
 * @author wilsonM
 * @date 2021年04月20日 3:38 下午
 * @description
 */
public class MyHashMapTest<K, V> {

    private int size = 0;
    private static int DEFAULT_CAPACITY = 1 << 4;
    private Entry<K, V>[] table;

    private MyHashMapTest() {
        table = new Entry[DEFAULT_CAPACITY];
    }

    private int size() {
        return size;
    }

    private V put(K key, V value) {
        int index = getIndex(key);
        //todo 注意这个地方的node一定要加泛型 不加泛型的value返回类型是Object
        for (Entry<K, V> node = table[index]; node != null; node = node.next) {
            //注意这个地方是那key进行equals
            //todo 针对put两次key为null的情景
            if (node.k == null || node.k.equals(key)) {
                V oldValue = node.v;
                node.v = value;
                return oldValue;
            }
        }
        //这是链表上没有值的情况
        table[index] = new Entry<K, V>(key, value, null);
        size++;
        return value;
    }

    public V get(K key) {
        int index = getIndex(key);
        //todo get 注意对table[0]的处理
        if (index == 0) {
            return table[0] != null ? table[0].v : null;
        }
        //todo 注意这个地方的node一定要加泛型
        for (Entry<K, V> node = table[index]; node != null; node = node.next) {
            if (node.k.equals(key)) {
                return node.v;
            }
        }
        return null;
    }


    //注意null值的处理
    private int getIndex(K key) {
        return key != null ? key.hashCode() & (DEFAULT_CAPACITY - 1) : 0;
    }

    //链表
    class Entry<K, V> {
        K k;
        V v;
        Entry<K, V> next;

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

        public K getK() {
            return k;
        }

        public V getV() {
            return v;
        }

        public Entry<K, V> getNext() {
            return next;
        }
    }

    public static void main(String[] args) {
        MyHashMapTest hashMap = new MyHashMapTest();

        hashMap.put(null, "meng");
        System.out.println("=======" + hashMap.get(null));
        hashMap.put(null, "zhao");
        System.out.println("=======" + hashMap.get(null));
        hashMap.put("1", "lu");
        System.out.println("=======" + hashMap.get("1"));
        hashMap.put("2", "ze");
        System.out.println("=======" + hashMap.get("2") + "     size:" + hashMap.size());
        hashMap.put("3", "quan");
        System.out.println("=======" + hashMap.get("3"));
        hashMap.put("1", "lzq");
        System.out.println("=======" + hashMap.get("1") + "      size:" + hashMap.size());
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值