自定义hashtable,可以自己做内存数据库,存放到数组链表当中去,取模的方式,来控制每个链表的数据均匀,也可以设置数组的长度来控制,链表内容的长度,提升查询效率.
package com.buba.hashtable;
public class Emp {
int id;
String name;
Emp next;
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
public Emp() {
}
}
package com.buba.hashtable;
public class EmpLink {
Emp head = null;
public void insert(Emp emp) {
Emp cur = this.head; //辅助指针
Emp pre = null; //辅助指针
if(cur == null){
this.head = emp;
return;
}
//如果不是一个空链表,给emp找到对应的位置并插入
while (true){
if(cur != null){
if(cur.id >= emp.id){
break;
}
pre = cur;
cur = cur.next;
}else{
break;
}
}
if(pre == null){
pre = emp;
pre.next = cur;
this.head = pre;
}else{
pre.next = emp;
emp.next = cur;
}
}
public void showLink() {
if(this.head == null){
System.out.println("链表为空");
return ;
}
Emp cur = this.head; //辅助指针
while(true){
if(cur != null){
System.out.println(cur.id+":"+cur.name);
cur = cur.next;
}else{
break;
}
}
}
//根据id查找对应的雇员
public void findById(int id) {
Emp cur = this.head;
while (true){
if(cur!=null && cur.id == id){
System.out.println("找到了"+cur.id+":"+cur.name);
return;
}
if(cur!=null && cur.next!=null){
cur = cur.next;
}else{
System.out.println("没有找到");
return;
}
}
}
//删除链表中的雇员
public void deleteById(int id) {
Emp cur = this.head;
if(cur!=null && cur.id == id){
this.head = cur.next;
return;
}
Emp pre = this.head;
cur = pre.next;
while (true){
if(cur!=null && cur.id == id){
pre.next = cur.next;
return;
}
pre = pre.next;
cur = cur.next;
if (cur == null){
System.out.println("没找到");
return;
}
}
}
}
package com.buba.hashtable;
public class HashTable {
EmpLink[] linkArr = new EmpLink[7];
{
for(int i=0;i<linkArr.length;i++){
linkArr[i] = new EmpLink();
}
}
public void insert(Emp emp){
int linkNum = hashFun(emp.id);
EmpLink empLink = this.linkArr[linkNum];
empLink.insert(emp);
}
public int hashFun(int id){
return id%7;
}
//显示所有的雇员
public void showAll(){
for(int i=0;i<linkArr.length;i++){
System.out.println("链表"+i);
this.linkArr[i].showLink();
}
}
//查找雇员
public void findById(int id){
int i = hashFun(id);
EmpLink links = linkArr[i];
links.findById(id);
}
//删除雇员
public void deleteById(int id){
int i = hashFun(id);
EmpLink links = linkArr[i];
links.deleteById(id);
}
}
package com.buba.hashtable;
public class TestHashTable {
public static void main(String[] args) {
HashTable hashTable = new HashTable();
hashTable.insert(new Emp(8,"kxj8"));
hashTable.insert(new Emp(22,"kxj22"));
hashTable.insert(new Emp(1,"kxj1"));
hashTable.insert(new Emp(15,"kxj15"));
hashTable.insert(new Emp(29,"kxj29"));
hashTable.showAll();
System.out.println("------------");
hashTable.findById(36);
System.out.println("------------");
hashTable.deleteById(36);
hashTable.showAll();
}
}