java - 无限循环遍历哈希表

标签 java hashtable

我正在尝试使用哈希表在数组中找到最常用的词。由于某种原因,while 循环无限循环。我已经调试过,并且该元素从未从它获得的第一个元素开始改变。关于为什么会发生这种情况的任何想法?

这是我的代码:

import java.util.Hashtable;

public class MyClass {
  public String mostPopularString (String []words) {
    if (words == null)
            return null;
    if (words.length == 0)
            return null;
    Hashtable<String, Integer> wordsHash = new Hashtable<String, Integer>();
    for (String thisWord : words)
    {
        if (wordsHash.containsKey(thisWord))
        {
            wordsHash.put(thisWord, wordsHash.get(thisWord) + 1);
        }
        else
        {
            wordsHash.put(thisWord, 1);
        }
    }
    Integer mostPopularCount = 0;
    String mostPopularWord = null;
    boolean tie = false;
    while (wordsHash.keys().hasMoreElements())
    {
        String currentWord = (String) wordsHash.keys().nextElement();
        if (wordsHash.get(currentWord) > mostPopularCount)
        {
            mostPopularCount = wordsHash.get(currentWord);
            mostPopularWord = currentWord;
            tie = false;
        }
        else if (wordsHash.get(currentWord) == mostPopularCount)
        {
            tie = true;
        }
    }
    if (tie)
        return null;
    else
        return mostPopularWord;
  }
}

最佳答案

您正在调用 wordsHash.keys()在循环的每次迭代中,都会给你一个新的 Enumeration<String>在每次迭代中 - 然后您将在内部循环中再次调用它。

您想调用它一次,然后遍历单个 Enumeration<String> :

Enumeration<String> iterator = wordsHash.keys();
while (iterator.hasMoreElements())
{
    String currentWord = iterator.nextElement();
    ...
}

请注意,由于您还获得了每个元素的值,因此最好迭代 entrySet()而不是 keys() .

最好使用HashMap而不是 Hashtable ,因为那时你可以只使用增强的 for 循环......

关于java - 无限循环遍历哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14612188/

相关文章:

loops - Powershell自定义对象-不传递foreach变量

java - 如何打印出循环发生的次数?

java - Hibernate:Criteria 和 createSQLQuery:如何获取正确的 JSON?

java - 无法使用 HttpClient POST 请求上传文件

arrays - Powershell:将数据从阵列中取出并放入新阵列中

java - 为什么我的 map 坏了?

java - 遍历 hashmap : 'For' loop using Random Access OR Iterator?

java - 显示按下的 Jbutton 的行和列

java - 将Java Restful服务连接到Matlab程序

c# - 使用键的克隆从哈希表中检索值; C#