哈希表查找使用最简单的除数取余法获得数据存放地址即下标,当位置冲突时,采用移位的方法解决。
代码:
/**
* The second constructor
* @param paraKeyArray The array of the keys.
* @param paraContentArray The array of contents.
* @param paraLength The space for the hash table.
*/
public DataArray(int[] paraKeyArray, String[] paraContentArray, int paraLength) {
//Step 1. Initialize
length = paraLength;
data = new DataNode[length];
for (int i = 0; i < length; i++) {
data[i] = null;
}// of for i
//Step 2. Fill the data.
int tempPosition;
for (int i = 0; i <paraKeyArray.length; i++) {
//Hash.
tempPosition = paraKeyArray[i] % paraLength;
//Find an empty position.
while (data[tempPosition] != null) {
tempPosition = ( tempPosition + 1) % paraLength;
System.out.println("Collision , move forward for key " + paraKeyArray[i]);
}// of while
data[tempPosition] = new DataNode(paraKeyArray[i],paraContentArray[i]);
}// of for i
}// of the second constructor
/**
* Hash search.
* @param paraKey The given key.
* @return The content of the key.
*/
public String hashSearch(int paraKey) {
int tempPosition = paraKey % length;
while (data[tempPosition] != null) {
if (data[tempPosition].key == paraKey) {
return data[tempPosition].content;
}// of if
System.out.println("Not this one for " + paraKey);
tempPosition = ( tempPosition + 1) % length;
}// of while
return "null";
}// of hashSearch
/**
* Test the hashSearch
*/
public static void hashSearchTest() {
int[] tempUnsortedKeys = { 16, 33, 38, 69, 57, 95, 86 };
String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while"};
DataArray tempDataArray = new DataArray(tempUnsortedKeys,tempContents,19);
System.out.println(tempDataArray);
System.out.println("Search result of 95 is: " + tempDataArray.hashSearch(95));
System.out.println("Search result of 38 is: " + tempDataArray.hashSearch(38));
System.out.println("Search result of 57 is: " + tempDataArray.hashSearch(57));
System.out.println("Search result of 4 is: " + tempDataArray.hashSearch(4));
}
单元测试结果:
------------------------hashSearch-----------------------
Collision , move forward for key 57
Collision , move forward for key 95
Collision , move forward for key 95
I am a data array with 19 item.
(38,else) (57,case) (95,for) null null null null null null null (86,while) null (69,switch) null (33,then) null (16,if) null null
Not this one for 95
Not this one for 95
Search result of 95 is: for
Search result of 38 is: else
Not this one for 57
Search result of 57 is: case
Search result of 4 is: null