HashMap的实现原理之自定义HashMap

自定义HashMap01

  1. 增加了put方法,实现了键重复时,覆盖对应的value值,hash值相同时在后面追加节点
package cn.hq.szxy;

/**
 * 自定义HashMap
 * 增加put方法,实现键重复时覆盖对应的value值
 * @author HQ
 */
public class HashMapTest02 {
    //位桶数组。bucket  array
    Node[] table;
    int size;                //存放的键值对的个数

    public HashMapTest02() {
        //长度一般定义成2的整数幂
        table = new Node[16];
    }

    public void put(Object key, Object value) {
        //定义了新的节点对象
        Node newNode = new Node();
        newNode.hash = myHash(key.hashCode(), table.length);
        newNode.key = key;
        newNode.value = value;
        newNode.next = null;

        Node temp = table[newNode.hash];
        //正在遍历的最后一个元素
        Node iterLast = null;
        boolean keyRepeat = false;
        if (temp == null) {
            //此处数组元素为空,则直接将新节点放进去
            table[newNode.hash] = newNode;
        } else {
            //此处数组元素不为空。则遍历对应链表。。
            while (temp != null) {
                //判断key如果重复,则覆盖
                if (temp.key.equals(key)) {
                    keyRepeat = true;
                    //只是覆盖value即可。其他的值(hash,key,next)保持不变。
                    temp.value = value;
                    break;
                } else {
                    //key不重复,则遍历下一个。
                    iterLast = temp;
                    temp = temp.next;
               }
            }
            //没有发生key重复的情况,则添加到链表最后。
            if (!keyRepeat) {
                iterLast.next = newNode;
            }
        }
    }
    public static void main(String[] args) {
        HashMapTest02 m = new HashMapTest02();
        m.put(10, "aa");
        m.put(20, "bb");
        m.put(30, "cc");
        m.put(20, "oooooo");//覆盖bb
        m.put(53, "gg");//hash值为5
        m.put(69, "hh");//hash值为5
        m.put(85, "kk");//hash值为5
        System.out.println(m);
    }
    
    public static int myHash(int v, int length) {
        return v & (length - 1);
    }
}

其对应的哈希表为:
在这里插入图片描述
ps:如有错误,欢迎各位同学指正

发布了12 篇原创文章 · 获赞 4 · 访问量 1754

猜你喜欢

转载自blog.csdn.net/Cymothoe/article/details/83900186