哈希表-------java实现

mac2026-04-22  5

今天太累了,不想写原理了,简单记一下供以后复习 简单的讲就是通过散列函数求出待插入/查找元素的位置,然后将其插入到那个位置的链表即实现,这里散列函数用的取模法

创建Person类,用作存储数据

class Person { public int id; public String name; public Person next; public Person(int id, String name) { this.id = id; this.name = name; } }

创建链表类

class PersonLinkedList { //头指针执行第一个Emp,因此链表的head直接指向第一个Emp private Person head; /** * 1.id自增 * 2.将员工直接添加到最后 * @param person */ public void add(Person person){ if (head==null){ head= person; return; } Person temp = head; while (true){ if (temp.next == null){ break;//到达链表最后 } temp = temp.next; } //添加到尾部 temp.next = person; } public void print(int num){ if (head==null){ System.out.println("链表"+(num+1)+"为空"); return; } Person temp=head; while (true){ if (temp == null){ break; } System.out.println("链表"+(num+1)+"的信息为==> id=>"+temp.id+":"+"name=>"+temp.name); temp=temp.next; } System.out.println(); } public Person findByid(int id){ if (head==null){ System.out.println("链表为空"); return null; } Person temp= head; while (true){ if (temp.id==id){ //找到 break; } if (temp.next==null){ //未找到 temp=null; break; } temp=temp.next; } return temp; } }

创建HashTable类

//创建HashTable class HashTable { private int size; //多少条链表 private PersonLinkedList[] personLinkedLists; public HashTable(int size) { this.size=size; personLinkedLists=new PersonLinkedList[size]; for (int i =0;i<size;i++){ //初始化每个链表 personLinkedLists[i]=new PersonLinkedList(); } } public void add(Person person){ //根据id得到其该添加到哪个链表 int personLinkedListNo = sanlie(person.id); //添加到对应链表 personLinkedLists[personLinkedListNo].add(person); } //遍历Hash链表 public void list(){ for (int i = 0;i < size; i++){ personLinkedLists[i].print(i); } } //根据id查找 public void findById(int id){ int listNo = sanlie(id); Person person = personLinkedLists[listNo].findByid(id); if (person !=null){ System.out.println("在第"+(listNo+1)+"个链表找到:"+"id:"+person.id+"name:"+person.name); }else { System.out.println("未找到目标"); } } //散列函数(取模法) public int sanlie(int id){ return id % this.size; } }
最新回复(0)