哈希表实现
哈希表实现实际上是一种存储方式,也是一种查找方法。查找过程中多了一步查找的运算(取余等),缩小了查找的范围
哈希表有很多种实现方法,直接定址法,除留取余法再散列函数法,链地址法等等
尚硅谷的实现方法中采用的是链地址法
复现之
package hashtab;
public class HashTabDemo
{
public static void main(String[] args)
{
Employee emp1 = new Employee(7, "xiaochuchu");
Employee emp2 = new Employee(14, "xiaolulu");
Employee emp3 = new Employee(1254, "xiaogougou");
Employee emp4 = new Employee(1473, "xiaogougou");
HashTab hat=new HashTab(7);
hat.add(emp1);
hat.add(emp2);
hat.add(emp3);
hat.add(emp4);
hat.list();
// 测试链表成功
// Employee emp1 = new Employee(10, "xiaochuchu");
// Employee emp2 = new Employee(11, "xiaolulu");
// Employee emp3 = new Employee(12, "xiaogougou");
// Employee emp4 = new Employee(13, "xiaogougou");
//
// EmpLinkedList empList = new EmpLinkedList();
// empList.add(emp1);
// empList.add(emp2);
// empList.add(emp3);
// empList.deleteEmp(12);
// empList.add(emp3);
// empList.add(emp4);
//
// empList.list();
}
}
class Employee
{
int id;
String name;
Employee next;
public Employee(int id, String name)
{
super();
this.id = id;
this.name = name;
}
@Override
public String toString()
{
return "[id=" + id + ", name=" + name + "]";
}
}
// 链表,管理哈希表中的一个成员
class EmpLinkedList
{
private Employee head = new Employee(0, "");
// 增
public void add(Employee emp)
{
if (emp != null)
{
Employee cur = head;
while (cur.next != null)
{
cur = cur.next;
}
cur.next = emp;
} else
{
System.out.println("输入参数有误,请重试");
}
}
// 删
public void deleteEmp(int id)
{
Employee cur = head;
if (head.next == null)
{
System.out.println("链表为空,没有找到对应的节点");
return;
}
while (true)
{
if (cur.next == null)
{
System.out.println("未找到相应的节点,删除失败");
break;
}
if (cur.next.id == id)
{
cur.next = cur.next.next;
System.out.println("删除成功");
break;
}
cur = cur.next;
}
}
// 改
// 查
public void list()
{
Employee cur = head.next;
while (cur != null)
{
System.out.print(cur.toString() + "\t");
cur = cur.next;
}
}
}
//建立哈希表
class HashTab
{
private EmpLinkedList[] empLinkedListArray;
private int size;
public HashTab(int size)
{
this.size=size;
empLinkedListArray=new EmpLinkedList[size];
//实例化引用
for (int i = 0; i < empLinkedListArray.length; i++)
{
empLinkedListArray[i]= new EmpLinkedList();
}
}
public void add(Employee emp)
{
int Nov=emp.id%size;
empLinkedListArray[Nov].add(emp);
}
public void list()
{
for (int i = 0; i < empLinkedListArray.length; i++)
{
System.out.println("第"+(i+1)+"个表");
empLinkedListArray[i].list();
System.out.println();
}
}
}