我正在尝试实现将存储Word对象的哈希集,但是当我向其添加多个单词对象时,它总是给我1个大小,我真的不知道这里的问题在哪里是我代码的某些部分:
public class HashWordSet implements WordSet{
private Node[] buckets = new Node[8];
private int size=0;
private class Node{
Word value;
Node next = null;
Node prev = null;
public Node (Word word){
value = word;
}
}
private int getBucketNumber(Word word){
int hash = word.hashCode();
if(hash<0){
hash = -hash;
}
return hash%buckets.length;
}
private void rehash(){
Node[] temp = buckets;
buckets = new Node[2*temp.length];
size = 0;
for (Node n : temp){
while (n != null){
add(n.value);
n = n.next;
}
}
}
@Override
public Iterator iterator() {
// TODO Auto-generated method stub
return null;
}
@Override
public void add(Word word) {
int pos = getBucketNumber(word);
Node node = buckets[pos];
while(node != null){
if(node.value.equals(word))
return;
else
node = node.next;
}
node = new Node(word);
node.next = buckets[pos];
buckets[pos] = node;
size++;
if(size == buckets.length)
rehash();
}
@Override
public boolean contains(Word word) {
// TODO Auto-generated method stub
return false;
}
@Override
public int size() {
return size;
}
public String toString() {
StringBuffer buf = new StringBuffer();
for (int i=0;i<buckets.length;i++) {
Node node = buckets[i];
if (node == null) continue;
buf.append("Bucket "+i+":");
while (node != null) {
buf.append(" "+node.value);
node = node.next;
}
buf.append("\n");
}
return buf.toString();
}
}
答案 0 :(得分:3)
在这里看起来你有一个逻辑SNAFU。你永远不会进入你的while循环。我在这里没有足够的代码来确定这是否是您遇到的唯一问题,但删除if检查肯定有帮助。
if (n == null){ // remove this
while (n != null){
add(n.value);
n = n.next;
}
}
答案 1 :(得分:1)
来自rehash()
的这些行似乎有误:
for (Node n : temp){
if (n == null){ //WRONG?!
while (n != null){
add(n.value);
n = n.next;
}
}
}
您只使用空值...