【发布时间】:2009-05-02 03:11:22
【问题描述】:
我正在为 java 中的哈希表编写一个类...你能确保我到目前为止做得正确吗?
我需要在其中存储 StudentRecord 对象....我正在根据 long 类型的学生 ID 计算哈希值...
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);
}
}
}
【问题讨论】:
-
这是作业吗?如果是这样,你应该这样标记这个问题。
-
在 java 中,有一个 [contract][1] 包括 .equals(Object) 和 .hashCode() 方法,允许您实现独立于键类型的哈希表。 [1]:java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html