Java HashSet 大小错误

标签 java

我正在尝试实现将存储 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();
}

最佳答案

看起来你这里有一个逻辑错误。你永远不会进入你的 while 循环。我这里没有足够的代码来确定这是否是您遇到的唯一问题,但是删除 if 检查肯定会有所帮助。

if (n == null){ // remove this
    while (n != null){ 
        add(n.value); 
        n = n.next; 
    }
} 

关于Java HashSet 大小错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33244133/

相关文章:

java - 从 Windows、Mac 和 Linux 上的位置检索文件

java - 用于 PDF 输出的 EPS 到 SVG 转换

java - 使用可执行 jar 时将配置文件加载到类路径中

java - 使用 java 创建 YouTube 事件而不提示从浏览器登录

java - 在浏览器上实现视频聊天的最佳方式

java - 使用 hibernate 和 ms sql server 驱动程序

java - 在 Swagger 中使用@ApiParam或@ApiModelProperty?

javascript - 需要从js文件引用Java全局变量

java - JSP:如何捕获另一个页面上的超链接文本

java - 两个 JVM 之间的共享内存