diff --git a/src/dataANDcalc/java/hash/EmpHashTable.java b/src/dataANDcalc/java/hash/EmpHashTable.java new file mode 100644 index 0000000..a0b569e --- /dev/null +++ b/src/dataANDcalc/java/hash/EmpHashTable.java @@ -0,0 +1,131 @@ +package hash; + +import com.sun.deploy.util.StringUtils; + +public class EmpHashTable { + + private EmpLinkedList[] empLinkedListArr; + + private final static int INIT_SIZE = 8; + + public EmpHashTable(){ + empLinkedListArr = new EmpLinkedList[INIT_SIZE]; + for (int i = 0; i < INIT_SIZE; i++) { + empLinkedListArr[i] = new EmpLinkedList(); + } + } + + public void put(int id, String name){ + EmpNode empNode = new EmpNode(id, name); + int index = hash(id); + EmpLinkedList empLinkedList = empLinkedListArr[index]; + empLinkedList.add(empNode); + } + + public void show(){ + for (int i = 0; i < empLinkedListArr.length; i++) { + System.out.println("第" + (i + 1) + "条链表"); + empLinkedListArr[i].show(); + } + } + + public String get(int id){ + int index = hash(id); + EmpLinkedList empLinkedList = empLinkedListArr[index]; + EmpNode empNode = empLinkedList.get(id); + if (empNode == null){ + return ""; + } + return empNode.name; + } + + public int hash(int id){ + return id % empLinkedListArr.length; + } + + public static class EmpLinkedList{ + + private EmpNode head; + + public void add(EmpNode empNode){ + if (head == null){ + head = empNode; + return; + } + EmpNode temp = head; + while (true) { + if (temp.next == null){ + temp.next = empNode; + return; + } + temp = temp.next; + } + } + + public void show(){ + EmpNode temp = head; + if (head == null){ + System.out.println("当前链表为空"); + return; + } + while (true){ + System.out.println(temp.toString()); + if (temp.next == null){ + break; + } + temp = temp.next; + } + } + + public EmpNode get(int id){ + EmpNode temp = head; + if (head == null){ + System.out.println("当前链表为空"); + return null; + } + while (true) { + if(temp.id == id){ + return temp; + } + if (temp.next == null){ + return null; + } + temp = temp.next; + } + } + } + + public static class EmpNode{ + private int id; + + private String name; + + private EmpNode next; + + public EmpNode(int id, String name) { + this.id = id; + this.name = name; + } + + @Override + public String toString() { + return "EmpNode{" + + "id=" + id + + ", name='" + name + '\'' + + ", next=" + next + + '}'; + } + } + + public static void main(String[] args) { + EmpHashTable empHashTable = new EmpHashTable(); + empHashTable.put(1, "张三"); + empHashTable.put(2, "李四"); + String name = empHashTable.get(1); + if (name != null && !"".equals(name)){ + System.out.println("找到了" + name); + } else { + System.out.println("未找到"); + } + } +}