package Chapter11;
import java.util.Scanner;
public class Hash {
/**
* @哈希表的建立和使用实例
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DataItem aDataItem;
int aKey,size,n,keysPerCell;
sop("Enter size of hash table: ");
size = Integer.parseInt(sc.nextLine()); //hashTable的大小
sop("Enter initial number of items: ");
n = Integer.parseInt(sc.nextLine()); //hashTable开始有的值
keysPerCell = 10;
HashTable theHashTable = new HashTable(size);
for(int j = 0;j<n;j++){
aKey = (int) (Math.random()*keysPerCell*size);
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
}
while(true){
sop("Enter first letter of: ");
sop("show , insert , delete , find : ");
char choise = sc.nextLine().charAt(0);
switch(choise){
case 's':
theHashTable.displayTable();
break;
case 'i':
sop("Enter key value to insert: ");
aKey = Integer.parseInt(sc.nextLine());
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
break;
case 'd':
sop("Enter key value to delete: ");
aKey = Integer.parseInt(sc.nextLine());
theHashTable.delete(aKey);
break;
case 'f':
sop("Enter key value to find: ");
aKey = Integer.parseInt(sc.nextLine());
aDataItem = theHashTable.find(aKey);
if(aDataItem==null)
sop("not find: "+aKey);
else
sop("find: "+aKey);
break;
default:
sop("invalid entry\n");
}
}
}
public static void sop(Object o){
System.out.print(o);
}
}
class DataItem{
private int iData;
public DataItem(int id){
iData = id;
}
public int getKey(){
return iData;
}
}
class HashTable{
private DataItem[] hashArray;
private int arraySize;
private DataItem nonItem;
public HashTable(int size){
arraySize = size;
hashArray = new DataItem[arraySize];
nonItem = new DataItem(-1);
}
public void displayTable(){
System.out.println("display table: ");
for(int i=0;i<arraySize;i++){
if(hashArray[i]!=null)
System.out.print(hashArray[i].getKey()+" ");
else
System.out.print("**");
}
System.out.println("-----------------------");
}
public int hashFunc(int key){
return key % arraySize;
}
public void insert(DataItem item){
int key = item.getKey();
int hashVal = hashFunc(key);
while(hashArray[hashVal]!=null && hashArray[hashVal].getKey()!=-1){
hashVal++;
hashVal = hashVal % arraySize;
}
hashArray[hashVal] = item;
}
public DataItem delete(int key){
int hashVal = hashFunc(key);
while(hashArray[hashVal]!=null){
if(hashArray[hashVal].getKey()==key){
DataItem temp = hashArray[hashVal];
hashArray[hashVal] = null;
return temp;
}
hashVal++;
hashVal = hashVal % arraySize;
}
return null;
}
public DataItem find(int key){
int hashVal = hashFunc(key);
while(hashArray[hashVal]!=null){
if(hashArray[hashVal].getKey() == key){
DataItem temp = hashArray[hashVal];
return temp;
}
hashVal++;
hashVal = hashVal % arraySize;
}
return null;
}
}