Created
April 9, 2016 23:26
-
-
Save davexpro/436e96d10f1e9a75021507a955ff5bf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pw.davex; | |
/** | |
* @author Dong Fang | |
*/ | |
public class HashTable <V> { | |
private int mTableSize; | |
private int mElementNum; | |
private int mAttemptTime; | |
private HashEntry[] mTable; | |
public HashTable(int pTableSize){ | |
mElementNum = 0; | |
mAttemptTime = 0; | |
mTableSize = pTableSize; | |
mTable = new HashEntry[mTableSize]; | |
} | |
/** | |
* @return the Size of HashTable | |
*/ | |
public int size(){ | |
return mTableSize; | |
} | |
/** | |
* @return the Element stored in HashTable | |
*/ | |
public int elementNum(){ | |
return mElementNum; | |
} | |
/** | |
* Hash the Key | |
* @param key | |
* @return hash | |
*/ | |
private int hash(int key) | |
{ | |
return (key & 0x7FFFFFFF) % mTableSize; | |
} | |
/** | |
* store the key and value into the HashTable | |
* @param key | |
* @param value | |
*/ | |
public synchronized void put(int key, V value) | |
{ | |
// Make sure the value is not null | |
if (value == null) { | |
throw new NullPointerException(); | |
} | |
int hash = hash(key); | |
// Makes sure the key is not already in the hashtable. | |
while(mTable[hash] != null) | |
hash = hash( hash + 1 ); | |
mTable[hash] = new HashEntry(hash,key,value); | |
// System.out.println("[+] " + key + " - " + hash); | |
mElementNum++; | |
} | |
/** | |
* get the value stored in the HashTable by key | |
* @param key | |
* @return the Value | |
*/ | |
public synchronized V get(int key) { | |
int hash = hash(key); | |
while(mTable[hash] != null) | |
{ | |
mAttemptTime++; | |
// System.out.println("[-] Hash: " + hash + " Key: " + key + " hashKey: " + mTable[hash].key); | |
if(mTable[hash].key == key) | |
return (V) mTable[hash].value; | |
hash = hash( hash + 1 ); | |
} | |
return null; | |
} | |
/** | |
* @return The average number of probes for all the searches. | |
*/ | |
public int getAvgPro(){ | |
return mAttemptTime / mElementNum; | |
} | |
/** | |
* reset the Probe attempts time of search | |
*/ | |
public void resetAttempt(){ | |
mAttemptTime = 0; | |
} | |
public class HashEntry<V> { | |
int hash; | |
int key; | |
V value; | |
HashEntry(int pHash, int key, V value) { | |
this.hash = pHash; | |
this.key = key; | |
this.value = value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment