1
我想實現散列集,它將存儲Word對象,但是當我添加多個單詞對象時,它給我總是大小1,我真的不知道這裏的問題在哪裏是一些部分我的代碼:Java HashSet錯誤的大小
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();
}
}
我剛更新了帖子,我把全班同學:// – Tano
我假設你有更多的錯誤?你有什麼試圖調試這個問題? – jgitter
我開始實施一步一步的方法,我現在沒有任何其他錯誤,因爲我只實現了兩種方法:/ – Tano