以下是我用java实现的哈希表
package com.husiwang.HashMap;
import com.husiwang.LinkList.LinkList;
/**
* Created by SiwangHu on 2015/2/5.
*/
public class HashMap {
private int Length; //长度
private int Capacity; //容量
private LinkList[] Key; //键
private LinkList[] Value; //值
private LinkList Keys; //键
private Visit Visited; //回调函数
private boolean[] Used; //占位
public HashMap(){
Length=0;
Capacity=100;
Visited=new Visit();
Keys=new LinkList();
Key=new LinkList[Capacity];
Value=new LinkList[Capacity];
Used=new boolean[Capacity];
for (int i = 0; i
Key[i]=new LinkList();
}
for (int i = 0; i
Value[i]=new LinkList();
}
for(int i=0;i
Used[i]=false;
}
}
public HashMap(int capacity){
if(capacity>0) {
Length=0;
Capacity = capacity;
Visited=new Visit();
Keys=new LinkList();
Key = new LinkList[Capacity];
Value = new LinkList[Capacity];
Used=new boolean[Capacity];
for (int i = 0; i
Key[i]=new LinkList();
}
for (int i = 0; i
Value[i]=new LinkList();
}
for(int i=0;i
Used[i]=false;
}
}
else{
throw new RuntimeException("容量不能为空");
}
}
public boolean IsEmpty(){
if(Length==0)
return true;
else
return false;
}
public int getLength() {
return Length;
}
public int getCapacity() {
return Capacity;
}
public LinkList getKeys() {
return Keys;
}
public int Hash(Object data){
return Math.abs(data.hashCode())%Capacity;
}
public void Put(Object key,Object value){
if(!HasKey(key)) {
int hash = Hash(key);
Used[hash]=true;
Keys.Insert(key);
Length++;
Key[hash].Insert(key);
Value[hash].Insert(value);
}
}
public Object Get(Object key){
if(HasKey(key)) {
int hash = Hash(key);
for (int i = 0; i
if (Key[hash].Get(i) == key) {
return Value[hash].Get(i);
}
}
return null;
}
else{
throw new RuntimeException("无此关键字");
}
}
public void Remove(Object key){
if(HasKey(key)) {
int hash = Hash(key);
for (int i = 0; i
if (Key[hash].Get(i) == key) {
Key[hash].Remove(i);
Value[hash].Remove(i);
Length--;
return;
}
}
}
}
public boolean HasKey(Object key){
return Keys.Find(key);
}
public void Traverse(){
Traverse(Visited);
}
public void Traverse(Visit visited){
for(int i=0;i
for(int j=0;j
if(Used[i]==true)
visited.visit(Key[i].Get(j),Value[i].Get(j));
}
}
}
}
package com.husiwang.HashMap;
import com.husiwang.LinkList.Node;
/**
* Created by SiwangHu on 2015/2/5.
*/
public class Visit {
public void visit(Object key,Object value){
System.out.println("Key="+key+" "+"value="+value);
}
}