数据结构——自写简易哈希表(Java)

这篇博客介绍了如何使用Java实现一个简单的哈希表,通过数组加链表的方式确保冲突解决。哈希表仅实现了添加元素和打印功能,哈希函数采用取模运算。代码中包含了一个节点类`Element`,一个链表类`ElemLinkedList`,以及哈希表类`Hash`,展示了如何在哈希表中存储和显示键值对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【1】HashTable原理

在这里插入图片描述

【2】说明

  • 通过数组加链表的方式实现
  • 只实现了添加和打印方法,其余方法类似

【3】代码:

	package algorithm.hashTable;

/**
 * 使用数组加链表的方式实现
 */
public class MyHashTable {
    public static void main(String[] args) {
        Hash hashTable = new Hash(5);
        Element e1 = new Element(2, "zjComing");
        Element e2 = new Element(45, "beijing");
        Element e3 = new Element(12, "ttttttt");
        Element e4 = new Element(60, "mmmmmmm");
        hashTable.add(e1);
        hashTable.add(e2);
        hashTable.add(e3);
        hashTable.add(e4);
        hashTable.show();
    }

}

//节点类
class Element {
    int id;
    String name;
    Element next;

    public Element(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

//数组中的每个元素,链表的头结点
class ElemLinkedList {
    Element head;

    //添加成员 添加到最后一个成员
    public void add(Element e) {
        if (head == null) {
            head = e;
            return;
        }
        Element temp = head;

        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        temp.next = e;
    }

    public void show(int no) {
        Element temp = head;
        while (temp != null) {
            System.out.printf("第 %d 个链表=> id是:%d 姓名:%s\t", no + 1, temp.id, temp.name);
            temp = temp.next;
        }
        System.out.println();
    }
}

//hash表
class Hash {
    private ElemLinkedList[] list;
    private int size;

    public Hash(int size) {
        this.size = size;
        list = new ElemLinkedList[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ElemLinkedList();
        }
    }

    //添加函数
    public void add(Element e) {
        int no = getNo(e.id);
        list[no].add(e);
    }

    public void show() {
        for (int i = 0; i < size; i++) {
            list[i].show(i);
        }
    }

    //hash函数
    private int getNo(int id) {
        return id % size;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值