哈希表基本功能实现

本文探讨了哈希表的基本操作,包括头插法和尾插法放入元素、扩容及找到key对应value的方法。强调了在使用自定义类作为HashMap的key时需要覆写hashCode和equals方法以确保正确性。此外,文章还分析了JDK1.7及之前使用头插法而JDK1.8改用尾插法的原因,以避免在多线程扩容时可能出现的环链表问题。
摘要由CSDN通过智能技术生成

上篇👇
二叉搜索树的基本操作

哈希表头插法放入元素

/**
 * user:ypc;
 * date:2021-05-20;
 * time: 11:05;
 */
public class HashBuck {
   

    class Node {
   
        public int key;
        int value;
        Node next;

        Node(int key, int value) {
   
            this.key = key;
            this.value = value;
        }
    }

    public int usedSize;
    public Node[] array;

    HashBuck() {
   
        this.array = new Node[8];
        this.usedSize = 0;
    }

    //JDk1.7及之前是头插法
    public void put1(int key, int value) {
   
        int index = key % this.array.length;
        Node node = new Node(key, value);
        Node cur = array[index];

        while (cur != null) {
   
            if (cur.key == key) {
   
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        node.next = array[index];
        array[index] = node;
        this.usedSize++;
        if (loadFactor() > 0.75) {
   
            resize1();
        }
    }
    public double loadFactor() {
   
        return this.usedSize / this.array.length * 1.0;
    }
}

哈希表尾插法放入元素

//JDK1.8是尾插法
    public Node findLast(Node head) {
   
        if (head == null) return head;
        Node cur = head;
        while (cur.next != null) {
   
            cur = cur.next;
        }
        return cur;
    }
    public void put2(int key, int value) {
   
        int index = key % this.array.length;
        Node node = new Node(key, value);
        Node cur = array[index];
        while (cur != null) {
   
            if (cur.key == key) {
   
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        Node last = findLast(array[index]);
        if (last == null) {
   
            array[index] = node;
            this.usedSize++
  • 16
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 33
    评论
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值