我正在为java中的哈希表编写一个类...请你确保我到目前为止正确地执行它.
我需要在其中存储StudentRecord对象....我正在根据学生的ID来计算哈希值,该ID类型为long ...
package proj3;
import java.util.LinkedList;
public class HashTable {
LinkedList<StudentRecord> [] buckets;
int size;
public HashTable(){
size = 10;
initialize();
}
public HashTable(int initialSize){
size = initialSize;
initialize();
}
private void initialize(){
for(int i=0; i<size; i++){
buckets[i] = new LinkedList<StudentRecord>();
}
}
/** for testing only
private int calculateHashString(String s){
int hash = 0;
for(int i=0; i<s.length(); i++){
hash += s.charAt(i);
}
return hash % size;
}
**/
private int calculateHash(long l){
return (int) (l % size);
}
public boolean contains(StudentRecord sr){
int hash = calculateHash(sr.studentID);
LinkedList<StudentRecord> l = buckets[hash];
if(l.contains(sr)){
return true;
}
return false;
}
public void put(StudentRecord sr){
int hash = calculateHash(sr.studentID);
LinkedList<StudentRecord> l = buckets[hash];
if(!l.contains(sr)){
buckets[hash].add(sr);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想你可能想编写单元测试来验证它的实际功能,而不管你的f(r)ie SO专家是否理智检查它.
超越简单测试用例的一个好处是将实现的功能与标准JDK HashMap进行比较; 生成随机密钥和/或值,插入,删除,并检查两个实现之间的状态是否相同(达到应有的程度).
| 归档时间: |
|
| 查看次数: |
4729 次 |
| 最近记录: |