java - 为什么在调整 HashTable 实现大小时会出现 OutOfMemoryError 错误?

标签 java hash out-of-memory hashtable

每次发生冲突时,我都会尝试 rehash() 我的 HashTable,但总是收到 Java 堆空间错误。

基本上,我有一个 String[] 表,每次哈希发生冲突时,我都希望将其长度乘以 2。

编辑:我在 while 循环中使用 insert(),该循环将大约 300.000 个单词加载到哈希表中。

 public void rehash() {
        String[] backup = table;
        size = size * 2;
        // i get the error on the line below
        table = new String[size];
        System.out.println("size" + size);
        for (int i = 0; i < backup.length; i++) {
            if (backup[i] != null) {
                insert(backup[i]);
            }

        }

   public void insert(String str) {

        int index = hashFunction(str);

        if (index > size || table[index] != null) {
            rehash();
        }

        table[index] = str;
    }

我的哈希函数:

int val= 0;
        val= s.hashCode();
        if (val< 0) {
            val*= -1;
        }

        while (val> this.size) {
            val%= this.size;
        }

        return val;


 public void load() {
        String str = null;
        try {
            BufferedReader in = new BufferedReader(new FileReader(location));
            while ((str = in.readLine()) != null) {
                insert(str);
            }
            in.close();
        } catch (Exception e) {
            System.out.println("exception");
        }
    }

最佳答案

从您发布的哈希函数来看,不清楚它返回什么,但看起来有问题。

int index = hashFunction(str);

如果您的索引不正确,那么您的代码会执行大量递归 new String[size]。在此处放置一个计数器或调试点并检查。

 if (index > size || table[index] != null) {
                rehash();
            }

关于java - 为什么在调整 HashTable 实现大小时会出现 OutOfMemoryError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29582247/

相关文章:

java - 使用 FreeMarker 流式传输巨大列表,内存不足异常

java - android.view.InflateException : Binary XML file line #2: Binary XML file line #2: Error inflating class <unknown>

java - 如何使用java生成条形码

c - 将冲突键哈希到哈希表中的下一个

python - 通过 python 脚本启动开膛手约翰

ruby - 将元素从 Ruby 哈希插入到 SQLite 3 的最快方法

java - Elasticsearch 单元测试

java - 将 xml 传递给 jquery 脚本的问题

java - Java SplashScreen 如何工作?

xml - 使用 data.zip 在 Clojure 中解析 XML 时出现 OutOfMemoryError